嗨,我有两张桌子实验和样本。我想创建一个触发器,这样每当我将一行插入到样本表中时,它就会拉出‘MySQL’表中由实验生成的最近的'Experiment_id‘,并拉入名为’MySQL_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时,生成样本id '1-6‘;当experiment_id 2由MySQL自动生成时,生成Sample_ id '7-10’。
我使用的是MySQL5.6。请来人帮帮我,谢谢!
发布于 2019-09-28 02:24:21
我不会用扳机的。只需在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);发布于 2019-09-28 02:12:45
您必须同时使用触发器来跟踪插入和更新:
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 ;使用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 ;https://stackoverflow.com/questions/58139493
复制相似问题