Example of LAST_INSERT_ID usage of MySQL environment: MySQL Sever 5.1 + MySQL command line tool first let's look at an example (the primary key is auto-incrementing): [SQL] mysql> insert into bankaccount (name, balance) values ('20140901', 123); Query OK, 1 row affected (1000 sec) mysql> insert into bankstatement (action, txdate, amt, toaccno, fromaccno) values ('20140901', curdate (), 122, 1, 2); Query OK, 1 row affected (1000 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 | Zhang San | 200 | 2 | Li Si | 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 | account opening | | 100 | NULL | 1 | 2 | account opening | 2012-10-14 | 1000 | NULL | 2 | 3 | query account information | 2012-10-14 | 0 | NULL | 2 | 4 | query an account information | 2012-10-14 | 0 | NULL | 1 | 5 | transfer | 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) Summary: LAST_INSERT_ID () returns the value of the AUTO_INCREMENT column in The Last INSERT or UPDATE statement.
References:
LAST_INSERT_ID usage of MySQL explain http://www.bkjia.com/database/201210/160986.html at http://www.bkjia.com/database/201206/137028.htmlmysql#:last_insert_id ()