Some sort of “different auto-increment indexes” per a primary key values

后端 未结 4 573
既然无缘
既然无缘 2020-12-07 04:24

I have got a table which has an id (primary key with auto increment), uid (key refering to users id for example) and something else which f

4条回答
  •  青春惊慌失措
    2020-12-07 05:30

    In a comment you ask the question about efficiency. Unless you are dealing with extreme volumes, storing an 8 byte DATETIME isn't much of an overhead compared to using, for example, a 4 byte INT.

    It also massively simplifies your data inserts, as well as being able to cope with records being deleted without creating 'holes' in your sequence.


    If you DO need this, be careful with the field names. If you have uid and id in a table, I'd expect id to be unique in that table, and uid to refer to something else. Perhaps, instead, use the field names property_id and amendment_id.

    In terms of implementation, there are generally two options.


    1). A trigger

    Implementations vary, but the logic remains the same. As you don't specify an RDBMS (other than NOT MS/Oracle) the general logic is simple...

    • Start a transaction (often this is Implicitly already started inside triggers)
    • Find the MAX(amendment_id) for the property_id being inserted
    • Update the newly inserted value with MAX(amendment_id) + 1
    • Commit the transaction

    Things to be aware of are...
    - multiple records being inserted at the same time
    - records being inserted with amendment_id being already populated
    - updates altering existing records


    2). A Stored Procedure

    If you use a stored procedure to control writes to the table, you gain a lot more control.

    • Implicitly, you know you're only dealing with one record.
    • You simply don't provide a parameter for DEFAULT fields.
    • You know what updates / deletes can and can't happen.
    • You can implement all the business logic you like without hidden triggers


    I personally recommend the Stored Procedure route, but triggers do work.

提交回复
热议问题