MySQL的LAST_INSERT_ID用法舉例
環境:MySQL Sever 5.1 + MySQL命令行工具
首先看個例子(主鍵是自增長):
[sql]
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)
www.2cto.com
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)
www.2cto.com
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列的值。
參考資料:
MySQL的LAST_INSERT_ID用法
http://www.BkJia.com/database/201208/151747.html;
mysql中的LAST_INSERT_ID()分析
http://www.BkJia.com/database/201206/137028.html
Mysql函數:Last_insert_id()語法講解
http://www.BkJia.com/database/201210/160986.html