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'.
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.
I am using 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 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.