INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`) VALUES ('Jay', '1', '55') WHERE (EXISTS SELECT id FROM NickNametbl WHERE `pmff`='1' AND `LName`='CN') OR (NOT EXISTS SELECT id FROM NickNametbl WHERE `LName`='CN' LIMIT 1)
上面的语句是失败的,请教正确的语句逻辑应该是怎么样?
实现目标的中文表达是:
1 、如果在 NickNametbl 表中,可以找到以下内容,
SELECT id FROM NickNametbl WHERE pmff
='1' AND LName
='CN';
2 、如果未能在 NickNametbl 表中找到内容,
SELECT id FROM NickNametbl WHERE LName
='CN' LIMIT 1;
1 和 2 是或的关系
3 、如果 1 或者 2 成立,就执行:
INSERT INTO PMnotyet
(LName
, type
, pmid
) VALUES ('Jay', '1', '55')
1
bootvue 2021-05-12 17:03:09 +08:00
```sql
INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`) VALUES ('Jay', '1', '55') WHERE EXISTS ( SELECT id FROM NickNametbl WHERE `pmff`='1' AND `LName`='CN') OR NOT EXISTS ( SELECT id FROM NickNametbl WHERE `LName`='CN' LIMIT 1) ``` 这个样子试一试 |
2
ChoateYao 2021-05-12 17:09:26 +08:00
INSERT INTO 不支持 where,我以为是 8.0 新特性,但是去查下 8.0 文档并没有支持该语法。
https://dev.mysql.com/doc/refman/8.0/en/insert.html |
3
qazwsxkevin OP |
4
kzm 2021-05-12 17:24:03 +08:00
INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`) select 'Jay', '1', '55' from dual WHERE EXISTS ( SELECT id FROM NickNametbl WHERE `pmff`='1' AND `LName`='CN') OR NOT EXISTS ( SELECT id FROM NickNametbl WHERE `LName`='CN' LIMIT 1) 试试
|
5
lybcyd 2021-05-12 17:38:44 +08:00
insert into 没有直接加 where 的语法。你可以把第一个 where 改成 select,根据第二个 where 的条件来生成结果,再将后半部分的结果直接插入 PMnotyet 表。另外你后面的语句也有点错误,需要调整一下。
INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`) SELECT 'Jay', '1', '55' WHERE EXISTS( SELECT id FROM NickNametbl WHERE `pmff` = '1' AND `LName` = 'CN' ) OR NOT EXISTS( SELECT id FROM NickNametbl WHERE `LName` = 'CN' LIMIT 1 ) 亲测可以生效 |
6
lybcyd 2021-05-12 17:42:00 +08:00
排版不太容易看,重新贴一下
```sql INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`) SELECT 'Jay', '1', '55' WHERE EXISTS(SELECT id FROM NickNametbl WHERE `pmff` = '1' AND `LName` = 'CN') OR NOT EXISTS(SELECT id FROM NickNametbl WHERE `LName` = 'CN' LIMIT 1) ``` |
7
controller 2021-05-12 17:58:32 +08:00
要么和 4 楼一样用 dual 表,要么写 sql 的 if ()then 解决,不过这样都是在插入语句内写入了查询,加大了主库的压力,主库应该尽可能的减少查询压力。如果是我,我选择表内设计唯一约束解决
|
8
xuanbg 2021-05-12 18:42:26 +08:00
正常 select 能出来结果集就行。INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`) select `LName`, `type`, `pmid` from NickNametbl where ……
|
9
CodeUtils 2021-05-13 10:57:49 +08:00
INSERT INTO `PMnotyet`(`LName`, `type`, `pmid`)
SELECT LName, type, pmid FROM NickNametbl WHERE EXISTS(SELECT id FROM NickNametbl WHERE `pmff` = '1' AND `LName` = 'CN') OR NOT EXISTS(SELECT id FROM NickNametbl WHERE `LName` = 'CN'); |