简体   繁体   中英

Update foreign key on INSERT INTO… SELECT

I have the following statement to insert values from one table (posts) into another (conversations):

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;

After each insert, I want to update the conversation_id column of posts to point to the newly inserted conversations row.

What's the best way of accomplishing this?

I think what you need is a trigger :

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$$

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM