mysql Getting the same auto_increment value into another

痞子三分冷 提交于 2019-12-11 16:04:52

问题


This may have a really easy answer. I have done much database stuff for a while. I am trying to get the auto_increment value from one table inserted into the value on another table. is there an easy way of doing this. For eg i have done:

CREATE TABLE table_a (
id int NOT NULL AUTO_INCREMENT,
a_value  varchar(4),
PRIMARY KEY (id)
);

CREATE TABLE table_b (
id int NOT NULL,
b_value varchar(15),
FOREIGN KEY (id) REFERENCES table_a (id)
);

Now i want to insert values into the table but I would like 'id' values for table_a and table_b to be the same. So far i have:

INSERT INTO table_a VALUES (NULL, 'foobar');

But I do not know how to go about extracting the auto_incermented 'id' number from table_a into the the 'id' value of table_b. I have looked at SELECT @id = LAST_INSERT_ID() but can not get it to work.


回答1:


You cannot do that at once. You'll have to first insert into the first table:

INSERT INTO table_a (a_value) VALUES ('foobar');

and then insert into the second using the generated id:

INSERT INTO table_b (id, b_value) VALUES (@@IDENTITY, 'foobar');



回答2:


LAST_INSERT_ID() and no need for the select statement part.



来源:https://stackoverflow.com/questions/4297462/mysql-getting-the-same-auto-increment-value-into-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!