在INSERT INTO ... SELECT上更新外键

时间:2012-02-08 19:44:53

标签: mysql sql

我有以下语句将值从一个表(帖子)插入另一个表(对话):

INSERT INTO conversations (subject, user_id, notify_me, invite_only, real_name_only, max_post_length, last_updated_at, created_at, updated_at)
SELECT subject, user_id, notify_me, invite_only, real_name_only, max_post_length, thread_updated_at, created_at, updated_at FROM posts WHERE ancestry IS null;

每次插入后,我想更新conversation_id的{​​{1}}列,指向新插入的posts行。

实现这一目标的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

我认为你需要的是一个触发器:

DELIMITER $$

CREATE TRIGGER AFTER INSERT ON `conversations` FOR EACH ROW
BEGIN
    UPDATE posts
        SET posts.conversation_id = NEW.Id
        WHERE
            posts.subject = NEW.subject
            AND posts.user_id = NEW.user_id
            AND posts.created_at = NEW.created_at;
END$$