gpt4 book ai didi

mysql - Insert based on Another Insert with mysql 插入

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:39 25 4
gpt4 key购买 nike

我必须在两个不同的表中运行两个插入语句。sql如下:

INSERT INTO Table1 ('t1_name', 't1_class') VALUES ('Joe','8');

Table1 有一个自动增量的 ti_id 列

INSERT INTO Table2 ('t2_ti_id','t2_course') VALUES(< 'ti_id' from Table1 call >,
'English'),(< 'ti_id' from Table1 call >, 'Math').

所以最终的结果应该是,table2 查询中使用了为 table1 查询设置的自动增量 id

Table1 

t1_id ti_name t1_class
1 Joe 8


Table2

t2_id t2_t1_id t1_course
1 1 English
2 1 Math

t1_id 和 t2_t1_id 有一个外键设置

请告诉我如何从同一个 sql 进行调用,这样我就不必为此制作一个单独的 perl 脚本

提前致谢

最佳答案

使用last_insert_id()

试试这个:

INSERT INTO Table1 (t1_name, t1_class) VALUES ('Joe','8');

SET @t1id = SELECT LAST_INSERT_ID();

INSERT INTO Table2 (t2_ti_id, t2_course)
VALUES (@t1id,'English')

关于mysql - Insert based on Another Insert with mysql 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23139259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com