假设:user表,有一个字段id,设置id为自增,执行一次insert语句,如何高效的获取刚刚插入的数据的id是多少?
原来的解决方案:执行insert之后,再执行一次select,找到刚刚插入的数据,拿到id,有没有可能优化这种方案?
天蓬老师2017-04-17 13:20:58
Assuming that the poster uses the best language in the world, then you can use the mysql_insert_id() function
怪我咯2017-04-17 13:20:58
Hibernate and other persistence tools can obtain the persistent object after saving, and the id inside is the id just inserted.
If there is no persistence layer, you can also use the SQL function LAST_INSERT_ID() to obtain the ID value of the AUTO_INCREACE field just inserted. The previous SQL must be an INSERT statement. If it is another statement, the returned ID value is zero.
黄舟2017-04-17 13:20:58
https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
Read comments
PHPz2017-04-17 13:20:58
Only talk about mysql
SELECT LAST_INSERT_ID();
Some database drivers will provide specialized methods, such as PDO::lastInsertId