我的数据库有一个名为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
处停止。应用程序有问题吗?或者我的查询错了?
答案 0 :(得分:52)
你必须使用
ALTER TABLE fruit ADD UNIQUE (name)
然后使用
INSERT IGNORE INTO fruit (name) VALUES ('mango')