gpt4 book ai didi

mysql - 不存在的地方 -- 错误 1064 (42000) : You have an error in your SQL syntax; check

转载 作者:行者123 更新时间:2023-11-29 11:13:15 25 4
gpt4 key购买 nike

只有当两个值(复合键)尚不存在时,我才想插入它们,否则 Mysql 会给出有关输入重复键的错误。

我的这个查询出现错误:

INSERT INTO group_msg_response (license_id,grp_id) VALUES (1,1) WHERE NOT EXISTS (SELECT 1 FROM group_msg_response WHERE license_id=1 AND grp_id=1 )

如果我单独运行它们,它们都运行良好。

它给出了这个错误:

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 1 FROM group_msg_response WHERE license_id=1 AND ' at line 1

可能是什么问题?我正在按照https://dev.mysql.com/doc/refman/5.5/en/exists-and-not-exists-subqueries.html中提到的方式进行操作

这是表定义:

create table IF NOT EXISTS  msg(
id INT UNSIGNED AUTO_INCREMENT ,
en varchar(5000),
hi varchar(5000),
PRIMARY KEY(id)
) ENGINE=InnoDB;



create table IF NOT EXISTS group_msg(
id INT UNSIGNED AUTO_INCREMENT ,
msg_id INT UNSIGNED,
lsource INT UNSIGNED NOT NULL,
browser CHAR(1) NOT NULL DEFAULT 'a' ,
expiry_date DATETIME NOT NULL ,
dated DATETIME NOT NULL,
deleteit TINYINT DEFAULT 0 ,
FOREIGN KEY (msg_id)
REFERENCES msg(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
PRIMARY KEY(id)
) ENGINE=InnoDB;



create table IF NOT EXISTS group_msg_response(
license_id MEDIUMINT,
grp_id INT UNSIGNED,
FOREIGN KEY (grp_id)
REFERENCES group_msg(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
PRIMARY KEY(license_id,grp_id)
) ENGINE=InnoDB;

最佳答案

使用选择,而不是:

INSERT INTO group_msg_response (license_id, grp_id) 
SELECT license_id, grp_id
FROM (SELECT 1 as license_id, 1 as grp_id) x
WHERE NOT EXISTS (SELECT 1
FROM group_msg_response gmr
WHERE gmr.license_id = x.license_id AND
gmr.grp_id = x.grp_id
);

或者,更好的是,让数据库通过创建唯一索引/约束来完成工作:

create unique index unq_gmr_license_grp on group_msg_response(license_id, grp_id) ;

然后您可以执行插入操作:

INSERT INTO group_msg_response (license_id, grp_id)
VALUES (1, 1)
ON DUPLICATE KEY UPDATE license_id = VALUE(license_id);

ON DUPLICATE KEY 子句除了防止错误发生之外什么也不做。

关于mysql - 不存在的地方 -- 错误 1064 (42000) : You have an error in your SQL syntax; check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com