如果项目不存在,则仅插入表格

时间:2014-01-04 23:45:43

标签: mysql sql insert

我的数据库有一个名为fruit的表:

fruit

+-------------+
| id | name   |
+ ----------- +
| 1  | apple  |
| 2  | orange |
| 3  | banana |
| 4  | grape  |
+-------------+

id是主键。我想在表中添加条目,但前提是它们不存在。

查询

IF NOT EXISTS (SELECT name FROM fruit WHERE name = 'mango')
INSERT INTO fruit (name) 
VALUES ('mango')

错误

我使用名为 Sequel Pro 的SQL GUI应用程序,此查询错误如下:

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 'IF NOT EXISTS (SELECT name FROM fruit WHERE name = 'mango') INSERT INTO frui' at line 1

也许

可能有些可疑。查询可能会在INSERT INTO frui处停止。应用程序有问题吗?或者我的查询错了?

1 个答案:

答案 0 :(得分:52)

你必须使用

ALTER TABLE fruit ADD UNIQUE (name) 

然后使用

INSERT IGNORE INTO fruit (name) VALUES ('mango')
相关问题