我想插入两个值(复合键),只有当这些值不存在时,否则Mysql会给出输入重复键的错误。
我的这个查询给出错误:
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
如果我单独运行它们,它们都运行良好。
它给出了这个错误:
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;
可能是什么问题?我正按照https://dev.mysql.com/doc/refman/5.5/en/exists-and-not-exists-subqueries.html
中提到的方式行事以下是表格定义:
manifest.json
答案 0 :(得分:1)
使用select
,而不是values
:
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
子句不执行任何操作 - 除了防止发生错误。