不存在的地方——错误 1064 (42000):您的 SQL 语法有误;查看

Where Not Exists -- ERROR 1064 (42000): You have an error in your SQL syntax; check

我只想在两个值(复合键)不存在时插入它们,否则 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

中提到的方式进行操作

这里是 table 定义:

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;

使用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
                     );

或者,更好的是,让数据库通过创建唯一的 index/constraint:

来完成工作
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 子句什么都不做 -- 除了防止错误发生。