首页  >  文章  >  数据库  >  MySQL的LAST_INSERT_ID用法举例

MySQL的LAST_INSERT_ID用法举例

WBOY
WBOY原创
2016-06-07 15:18:281075浏览

环境:MySQL Sever 5.1 MySQL命令行工具 首先看个例子(主键是自增长): 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)

环境:MySQL Sever 5.1 + MySQL命令行工具

首先看个例子(主键是自增长):


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



声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn