选择最后插入的id并插入MY SQL中的第二个表

时间:2014-05-21 12:19:26

标签: mysql

我是我的新手,并且遇到了疑问。我正在使用的查询如下;

insert into tableA(fname, lname) values('hello','world');
@id=SELECT LAST_INSERT_ID();
insert into tableB(x,y) values('good', @id);

但我在下面收到错误;

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@id=SELECT LAST_INSERT_ID()' at line 2 

请有人建议我在这里做错了,先谢谢。

2 个答案:

答案 0 :(得分:2)

您错过了set

insert into tableA(fname, lname) values('hello','world');
set @id=SELECT LAST_INSERT_ID();
insert into tableB(x,y) values('good', @id);

答案 1 :(得分:2)

关闭。

insert into tableA(fname, lname) values('hello','world');
SET @id = LAST_INSERT_ID();
insert into tableB(x,y) values('good', @id);

结果:

mysql> insert into tableA(fname, lname) values('hello','world');
Query OK, 1 row affected (0.07 sec)

mysql> SET @id = LAST_INSERT_ID();
Query OK, 0 rows affected (0.00 sec)