INSERT INTO personOffice(personID, officeID)
SELECT '2', (SELECT officeID FROM offices WHERE title = 'Berlin') FROM dual
WHERE NOT EXISTS (SELECT * FROM personOffice WHERE personId = 2 AND officeID = 1)
SQL Insert when not exists
Question
I searched a while for this problem, but I can't solve it...
I want to check if a record doesn't exists in a mysql table and then insert a record.
Here is my code:
IF NOT EXISTS (SELECT * FROM personOffice WHERE personID = 2 AND officeID = 1)
BEGIN
INSERT INTO personOffice (personID, officeID) VALUES ('2', (SELECT officeID FROM offices WHERE title = 'Berlin'))
END
Mysql tells me that theres a syntax-error in my first line.
Thanks for your solutions.
Solution
OTHER TIPS
You might try this :
INSERT INTO personOffice (personID, officeID)
VALUES ('2', (SELECT officeID FROM offices WHERE title = 'Berlin'))
WHERE NOT EXISTS (SELECT * FROM personOffice WHERE personID = 2 AND officeID = 1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow