I have a table user
. It has columns id
and email
.
USER TABLE
id | email
1 | xxx@gmail.com
2 | yyy@gmail.com
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 theAUTO_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 thatid
is theAUTO_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;