我一直在尝试在数据库中插入一条记录(如果该记录尚不存在),这是查询:
insert into evt(e_id, t_id)
values( '1597', '4')
where not exists( select id from evt where e_id = '4' and t_id = '1597');
该查询返回并出现以下错误:
ERROR 1064 (42000): 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 evt where e_id = '4' and t_id = ' at line 1
我不明白为什么它不起作用
最佳答案
如果您想防止数据库中出现重复项,那么就让数据库来完成这项工作。使用唯一约束或索引:
create unique index unq_evt_eid_tid on evt(e_id, t_id);
无论如何插入或更新值,这都可以保证数据完整性。数据库会为您完成这项工作。
然后,您可以通过使用重复键更新
来防止插入时出现错误:
insert into evt(e_id, t_id)
values (1597, 4)
on duplicate key update e_id = values(e_id);
重复键
可防止代码生成错误。
我还从值中删除了单引号。 Id 通常是数字。如果它们确实是字符串,请重新添加引号。
关于MySQL语法错误: where not exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44747283/