Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql insert query with condition - not exist [closed]

Tags:

php

mysql

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?

like image 898
user3642988 Avatar asked May 26 '26 09:05

user3642988


1 Answers

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
like image 147
jewelhuq Avatar answered May 27 '26 23:05

jewelhuq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!