Defining Composite Key with Auto Increment in MySQL

后端 未结 5 1459
心在旅途
心在旅途 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

    You can't have MySQL do this for you automatically for InnoDB tables - you would need to use a trigger or procedure, or user another DB engine such as MyISAM. Auto incrementing can only be done for a single primary key.

    Something like the following should work

    DELIMITER $$
    
    CREATE TRIGGER xxx BEFORE INSERT ON issue_log
    FOR EACH ROW BEGIN
        SET NEW.sr_no = (
           SELECT IFNULL(MAX(sr_no), 0) + 1
           FROM issue_log
           WHERE app_id  = NEW.app_id
             AND test_id = NEW.test_id
        );
    END $$
    
    DELIMITER ;
    

提交回复
热议问题