2015-09-23 69 views
3

我試圖用條件將數據添加到表中 - 如果數據已經存在 - 不要添加它。我不想用INSERT IGNORE INTO帶插入條件的sql插入查詢 - 不存在

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 
         ) 

錯誤:

#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

有誰知道什麼是錯我的發言?

+2

'INSERT'沒有'WHERE'子句。 http://dev.mysql.com/doc/refman/5.6/en/insert.html – Sean

回答

1

讓我的回答你的問題

如果使用WHERE NOT存在,您需要編寫代碼的方式如下:

INSERT INTO alerts (type,id,....) 
SELECT 'COL1 VALUE', 'COL2 VALUE' 
WHERE NOT EXISTS (SELECT * FROM TABLE_1 WHERE COL1='COL1 VALUE'); 

或者你可以用另一種方式來做到這一點。

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