I'm trying to add data to a table with the condition - if data is already exist - don't add it. I don't want to use INSERT IGNORE INTO
SQL:
INSERT INTO `alerts` (type, userID, fromID, refID, createDate)
VALUES ('commentReply', 2, 1, 452, 1443048940)
WHERE NOT EXISTS (SELECT *
FROM alerts
WHERE `type` = 'commentReply'
AND userID = 2
AND viewed = 0
)
Error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT id FROM alerts WHERE `type` = 'commentR' at line 3
Does anyone know what is wrong with my statement?
Let my answer your question
If you use WHERE NOT EXIST you need to write the code in the following way:
INSERT INTO alerts (type,id,....)
SELECT 'COL1 VALUE', 'COL2 VALUE'
WHERE NOT EXISTS (SELECT * FROM TABLE_1 WHERE COL1='COL1 VALUE');
Or you can use another way to do it.
IF (SELECT COUNT(*) FROM alerts WHERE yourcondition > 0)
UPDATE alerts SET c1=(SELECT id FROM beta WHERE yourcondition)
ELSE
BEGIN
INSERT INTO alerts (names..) VALUES (values...)
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With