我有一个没有主键和两列的表。当表为空时,此查询应生成一条记录,当此记录已存在时,它不应该。
INSERT INTO traffic (traffic_time, traffic_amount)
SELECT '13:00:00', '24' FROM traffic
WHERE NOT EXISTS (SELECT * FROM traffic WHERE traffic_time = '13:00:00' AND
traffic_amount = '24')
但是在运行时,即使没有重复项,也不会插入任何行。
我尝试使用其他答案,如:
INSERT INTO traffic (traffic_time, traffic_amount)
SELECT '13:00:00','24'
WHERE NOT EXISTS (SELECT * FROM traffic WHERE traffic_time = '13:00:00' AND
traffic_amount = '24') LIMIT 1
但是这个给了我一个“错误代码1064 SQL语法错误”,即使它在语法上是正确的。
如何在不添加主键的情况下解决此问题?
注意:我看过类似的S.O.线程但无法解决此问题。这些答案来自那些线程
答案 0 :(得分:1)
关注link from my comment ...
INSERT INTO traffic (t1, t2)
SELECT *
FROM (SELECT
'24' as tmp1,
'24' as tmp2) as tmp
WHERE NOT EXISTS(
SELECT t1, t2
FROM traffic
WHERE t1 = '24' AND
t2 = '24'
)
LIMIT 1;