Get the id of a row when UNIQUE KEY is violated

前端 未结 2 571
遇见更好的自我
遇见更好的自我 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:18

    In scaning by UNIQUE KEY BTREE is used so it's quite fast.

    Don't you want check for existing of value by yourself in additional select query

    0 讨论(0)
  • 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;
    0 讨论(0)
提交回复
热议问题