MySQL语法错误: where not exists

标签 mysql sql

我一直在尝试在数据库中插入一条记录(如果该记录尚不存在),这是查询:

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/

相关文章:

php - 上载多个图像并将其路径存储在数据库中

php - 停止动态下拉列表中的重复行

php - 得到减去当前 Y-m 后的月数

带有if语句的Mysql触发器不起作用

java - 将字符串转换为字节 - Java

MySQL - 对连接表进行 AND 查询

mysql - SQL NOT IN 仍包含应排除的行

java - RuntimeException : org. hibernate.exception.SQLGrammarException:无法执行查询

mysql - 用数据库中的数据填充数据表

sql - 具有顺序演算的 LAG 函数