Home > Net >  MySQL - Insert foreign key if not exist
MySQL - Insert foreign key if not exist

Time:11-28

First i have a table users:

id name lastname username
1 John Doe mr44

Then i have a table comments, user_id is a FOREIGN KEY of users table

id user_id
1 1

I am inserting the user_id with the following query:

INSERT INTO comments(user_id)
VALUES ((SELECT id FROM users WHERE username = "mr44"));

What i want to do now is insert the user_id only if it doesn't exist.

I tried something like this but it didn't work:

INSERT INTO comments(user_id)
VALUES (
(SELECT id FROM users WHERE username = "mr44")

    WHERE NOT EXISTS (SELECT * FROM comments  
    WHERE user_id = 1 LIMIT 1)
);

CodePudding user response:

I managed to found an answer that works

INSERT IGNORE INTO comments (user_id)
SELECT * FROM (SELECT id from users WHERE username = "mr44") AS temp
WHERE NOT EXISTS (
  SELECT user_id FROM comments WHERE user_id = 19
) LIMIT 1;
  • Related