我有以下sql查询,只有在表
中不存在时才会插入INSERT INTO message_log (message, from_id, to_id, match_id, unix_timestamp, own_account) VALUES('hi', 'tom', 'tom', '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040', 33333, TRUE)
WHERE NOT EXISTS (SELECT 1 FROM message_log WHERE message = 'hi' AND from_id = 'tom' AND to_id = 'tom' AND match_id = '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040' AND unix_timestamp = 33333)
但是我收到以下错误
ERROR: syntax error at or near "WHERE"
LINE 2: WHERE NOT EXISTS (SELECT 1 FROM message_log where message = ...
^
我做错了什么?
答案 0 :(得分:1)
仅当该记录不存在时,才在表中插入记录:
INSERT INTO message_log (message, from_id, to_id, match_id, unix_timestamp, own_account)
SELECT 'hi', 'tom', 'tom', '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040', 33333, TRUE
FROM message_log
WHERE NOT EXISTS (SELECT 1 FROM message_log WHERE message = 'hi' AND from_id = 'tom' AND to_id = 'tom' AND match_id = '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040' AND unix_timestamp = 33333)
它有点冗长,但它应该做你想要的。或者,您可以在表上设置唯一的主键,因此如果您尝试插入重复键,数据库将为您提供击键。一个中的六个,另一个中的六个。
答案 1 :(得分:0)
以下内容应该
INSERT INTO message_log (message, from_id, to_id, match_id, unix_timestamp, own_account)
SELECT 'hi', 'tom', 'tom', '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040', 33333, TRUE
WHERE NOT EXISTS (SELECT 1 FROM message_log WHERE message = 'hi' AND from_id = 'tom'
AND to_id = 'tom' AND match_id = '55640ec48a2aecab0e3c096c556f5435f4bb054c68930040'
AND unix_timestamp = 33333)
然而它缺少styke:self query。
也许以下内容可能适用:
INSERT ...
ON DUPLICATE KEY UPDATE own_account = own_account;