日期:2014-05-16 浏览次数:21003 次
首先看个例子(主键是自增长):
mysql> insert into bankaccount(name,balance) values('123', 1000); Query OK, 1 row affected (0.06 sec) mysql> insert into bankstatement(action, txdate, amt, toaccno, fromaccno) values ('122', curdate(), 1000, 1, 2); Query OK, 1 row affected (0.00 sec) mysql> select last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 7 | +------------------+ 1 row in set (0.00 sec) mysql> select * from bankaccount; +-------+------+---------+ | accno | name | balance | +-------+------+---------+ | 1 | 张三 | 200 | | 2 | 李四 | 900 | | 3 | 123 | 1000 | | 4 | 123 | 1000 | +-------+------+---------+ 4 rows in set (0.00 sec) mysql> select * from bankstatement; +----+--------------+------------+------+---------+-----------+ | id | action | txdate | amt | toaccno | fromaccno | +----+--------------+------------+------+---------+-----------+ | 1 | 开户 | 2012-10-14 | 100 | NULL | 1 | | 2 | 开户 | 2012-10-14 | 1000 | NULL | 2 | | 3 | 查找账户信息 | 2012-10-14 | 0 | NULL | 2 | | 4 | 查找账户信息 | 2012-10-14 | 0 | NULL | 1 | | 5 | 转账 | 2012-10-14 | 100 | 1 | 2 | | 6 | 122 | 2012-10-14 | 1000 | 1 | 2 | | 7 | 122 | 2012-10-14 | 1000 | 1 | 2 | +----+--------------+------------+------+---------+-----------+ 7 rows in set (0.00 sec)
总结:LAST_INSERT_ID()返回最后一个INSERT或UPDATE语句中AUTO_INCREMENT列的值。
参考资料:
http://zhaohe162.blog.163.com/blog/static/38216797201122411193745/
http://it.100xuexi.com/view/otdetail/20120619/73a6cc8f-36b8-4b70-8904-57c18d3ab385.html
http://blog.csdn.net/wh62592855/article/details/6722298