[英]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
Hi I have two tables Experiment and Sample.嗨,我有两张桌子实验和样品。 I want to create a trigger such that whenever I insert a row into Sample table it should pull the recent 'Experiment_id' that is generated by MySQL in the 'Experiment' table and pull into a column of 'Sample' table named 'Experiment_id'.
我想创建一个触发器,这样每当我在 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
So Sample id '1-6' is generated when there is only 'Experiment_id' 1 is existing in the 'Experiment' table and Sample_ id '7-10' is generated when experiment_id 2 is auto generated by MySQL.因此,当“Experiment”表中仅存在“Experiment_id”1 时生成 Sample_id“7-10”,当 MySQL 自动生成experiment_id 2 时生成 Sample_id“7-10”。
I am using mysql 5.6.我正在使用 mysql 5.6。 Please someone help me, thanks!!
请哪位大神帮帮我,谢谢!!
You will have to use both trigger to track insert and update:您将不得不同时使用触发器来跟踪插入和更新:
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 ;
Use update trigger to track update:使用更新触发器来跟踪更新:
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 ;
I wouldn't use a trigger for that.我不会为此使用触发器。 Just use a subquery in the INSERT statement:
只需在 INSERT 语句中使用子查询:
INSERT INTO SAMPLE (sample_name, Experiment_id) VALUES (
'sample name',
(SELECT MAX(Experiment_id) FROM EXPERIMENT)
)
If you want to do it with a trigger, try this:如果你想用触发器来做,试试这个:
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.