gpt4 book ai didi

mysql - 每次使用触发器插入 MySQL 5.6 中的目标表后,尝试将上次更新的 row_id 从源表拉到另一个表

转载 作者:行者123 更新时间:2023-11-29 15:37:00 25 4
gpt4 key购买 nike

嗨,我有两个表“实验”和“示例”。我想创建一个触发器,这样每当我在 Sample 表中插入一行时,它都应该拉出 MySQL 在“Experiment”表中生成的最新“Experiment_id”,并拉入“Sample”表中名为“Experiment_id”的列。

EXPERIMENT TABLE
Experiment_id(auto_incremented) Exp_name
1 abc

SAMPLE TABLE
Sample_id Experiment_id sample_name
1 1
2 1
3 1
4 1
5 1
6 1

**New Entry Exp name - xyz**

EXPERIMENT TABLE
Experiment_id(auto_incremented) Exp_name
1 abc
2 xyz

SAMPLE TABLE
Sample_id Experiment_id sample_name
1 1
2 1
3 1
4 1
5 1
6 1
7 2
8 2
9 2
10 2

因此,当“Experiment”表中仅存在“Experiment_id”1 时,会生成 Sample id“1-6”,而当“experiment_id”2 由 MySQL 自动生成时,会生成 Sample_id“7-10”。

我使用的是mysql 5.6。请有人帮助我,谢谢!!

最佳答案

我不会为此使用触发器。只需在 INSERT 语句中使用子查询即可:

INSERT INTO SAMPLE (sample_name, Experiment_id) VALUES (
'sample name',
(SELECT MAX(Experiment_id) FROM EXPERIMENT)
)

如果您想使用触发器来执行此操作,请尝试以下操作:

create trigger SAMPLE_before_insert before insert on SAMPLE FOR EACH ROW 
set new.Experiment_id = (select max(Experiment_id) from EXPERIMENT);

关于mysql - 每次使用触发器插入 MySQL 5.6 中的目标表后,尝试将上次更新的 row_id 从源表拉到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139493/

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