MySQL插入不存在/如果不存在
问题描述:
我尝试了以下查询:
INSERT INTO `surfed_site` (user, site)
VALUES ('123', '456')
WHERE NOT EXISTS (SELECT site FROM `surfed_site` WHERE site=456)
但是我不断收到MySQL错误:
But I keep getting a MySQL error:
我不知道我在做什么错,有人可以指导我吗?
I have no clue what I'm doing wrong, would anybody be able to guide me?
答
INSERT
语句支持两种 1 语法:一种使用VALUES
,一种使用查询.您不能将它们组合在一起,只有查询语法支持WHERE
条款.所以:
INSERT
statements support two1 syntaxes: one that uses VALUES
, and one that uses a query. You can't combine them, and only the query syntax supports WHERE
clauses. So:
INSERT INTO `surfed_site` (user, site)
SELECT '123', '456' FROM (SELECT 1) t
WHERE NOT EXISTS (SELECT site FROM `surfed_site` WHERE site=456)
- 实际上是三种语法;您也可以使用
SET
.如果您只插入一条记录,则该条记录在功能上等同于VALUES
,但可读性更高.
- Actually three syntaxes; you can also use
SET
. If you're only inserting one record, this one is functionally equivalent toVALUES
, but arguably more readable.