Get the id of a row when UNIQUE KEY is violated

前端 未结 2 573
遇见更好的自我
遇见更好的自我 2021-01-25 04:35

I have a table user. It has columns id and email.

USER TABLE

id | email
1  | xxx@gmail.com
2  | yyy@gmail.com
         


        
2条回答
  •  终归单人心
    2021-01-25 05:19

    Use INSERT ... ON DUPLICATE KEY UPDATE, then get the autoincremented id as usual:

    If a table contains an AUTO_INCREMENT column and INSERT ... ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. Exception: For updates, LAST_INSERT_ID() is not meaningful prior to MySQL 5.1.12. However, you can work around this by using LAST_INSERT_ID(expr). Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:

    INSERT INTO table (a,b,c) VALUES (1,2,3)
      ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;

提交回复
热议问题