gpt4 book ai didi

mysql - 根据table1中特定列的输入自动添加table2中的行

转载 作者:行者123 更新时间:2023-11-29 12:55:59 25 4
gpt4 key购买 nike

我的 mysql(phpmyadmin) 数据库中有两个表:table1 和 table2。

Table1 包含列:id1(自动递增)、desc1 和 num。表2包含列:id2,desc2,id1(来自表1)和desc1(来自表1)。

首先,当我在 table1 中添加行时,table2 中会自动添加与 num 中提供的值相同数量的行。

其次,id2 应该针对相同的 id1 自动递增。当 id1 发生变化时,id2 应该再次从 1 开始。

如何实现这一目标?

最佳答案

使用触发器实现此目的的一种方法,例如

delimiter //
create trigger ins_table2 after insert on table1
for each row
begin
declare t2_cnt_index int default 1;
while t2_cnt_index <= new.num do
insert into Table2 (desc2,id1) values (new.desc2,new.id1);
set t2_cnt_index := t2_cnt_index + 1;
end while ;
end ; //
delimiter ;

关于mysql - 根据table1中特定列的输入自动添加table2中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24063599/

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