[英]Pull one column from source table to another table after every insert into the destination table in MySQL 5.6 using a trigger
[英]Trying to pull the Last updated row_id from source table to another table after each insert into the destination table in MySQL 5.6 using a trigger
嗨,我有两张桌子实验和样品。 我想创建一个触发器,这样每当我在 Sample 表中插入一行时,它应该拉取由 MySQL 在“Experiment”表中生成的最近的“Experiment_id”,并拉入名为“Experiment_id”的“Sample”表的列中。
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“7-10”,当 MySQL 自动生成experiment_id 2 时生成 Sample_id“7-10”。
我正在使用 mysql 5.6。 请哪位大神帮帮我,谢谢!!
您将不得不同时使用触发器来跟踪插入和更新:
DROP TRIGGER IF EXISTS trigger_experiment_after_insert;
DELIMITER $$
CREATE TRIGGER trigger_experiment_after_insert
AFTER INSERT ON experiment FOR EACH ROW
BEGIN
-- sample_id will be auto_increment
INSERT INTO sample_log SET experiment_id = NEW.experiment_id;
END; $$
DELIMITER ;
使用更新触发器来跟踪更新:
DROP TRIGGER IF EXISTS trigger_experiment_after_update;
DELIMITER $$
CREATE TRIGGER trigger_experiment_after_update
AFTER UPDATE ON experiment FOR EACH ROW
BEGIN
-- sample_id will be auto_increment
INSERT INTO sample_log SET experiment_id = OLD.experiment_id;
END; $$
DELIMITER ;
我不会为此使用触发器。 只需在 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.