Defining Composite Key with Auto Increment in MySQL

后端 未结 5 1454
心在旅途
心在旅途 2020-12-01 04:01

Scenario:

I have a table which references two foreign keys, and for each unique combination of these foreign keys, has its own auto_increment column

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 04:18

    I don't fully understand your increment requirement on the test_id column, but if you want an ~autoincrement sequence that restarts on every unique combination of (app_id, test_id), you can do an INSERT ... SELECT FROM the same table, like so:

    mysql> INSERT INTO `issue_log` (`sr_no`, `app_id`, `test_id`, `issue_name`) SELECT
               IFNULL(MAX(`sr_no`), 0) + 1 /* next sequence number */,
               3 /* desired app_id */,
               1 /* desired test_id */,
               'Name of new row'
               FROM `issue_log` /* specify the table name as well */
           WHERE `app_id` = 3 AND `test_id` = 1 /* same values as in inserted columns */
    

    This assumes a table definition with no declared AUTO_INCREMENT column. You're essentially emulating autoincrement behavior with the IFNULL(MAX()) + 1 clause, but the manual emulation works on arbitrary columns, unlike the built-in autoincrement.

    Note that the INSERT ... SELECT being a single query ensures atomicity of the operation. InnoDB will gap-lock the appropriate index, and many concurrent processes can execute this kind of query while still producing non-conflicting sequences.

提交回复
热议问题