0

根据我在此处找到的上一篇文章,当第一个表的状态发生变化时,我能够将值插入到第二个表中,但它会不断添加,我需要检查 submit_id 是否已经插入到第二个表中,然后更新字段没有插入它增益,我将如何在触发器执行之前进行检查?因为 new.status 和 old.status 指的是正在编辑的行而不是它正在插入的表上的行,我如何比较它并插入或更新如果它已经存在,谢谢

4

1 回答 1

1

You can use INSERT INTO ... ON DUPLICATE KEY UPDATE syntax for that

If order for it to work properly you have to have a UNIQUE constraint on submitId column in your second table (let's call it students).

ALTER TABLE students ADD UNIQUE (submitId);

Now an improved version of a trigger

DELIMITER $$
CREATE TRIGGER tg_au_submissions
AFTER UPDATE ON submissions
FOR EACH ROW
BEGIN
  IF NEW.status = 1 THEN
    INSERT INTO students (submitId, studentName, submitDate, contacts, email) 
    VALUES (NEW.submitId, NEW.studentName, NEW.submitDate, NEW.contacts, NEW.email)
    ON DUPLICATE KEY UPDATE 
      studentName = VALUES(studentName),
      submitDate = VALUES(submitDate),
      contacts = VALUES(contacts),
      email = VALUES(email);
  END IF;
END$$
DELIMITER ;

Here is SQLFiddle demo

于 2013-08-11T04:42:48.103 回答