我的数据库有一个名为的表fruit:
fruit
+-------------+ | id | name | + ----------- + | 1 | apple | | 2 | orange | | 3 | banana | | 4 | grape | +-------------+
id是主键。我想将条目添加到表中,但前提是它们尚不存在。
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。应用程式有问题吗?还是我的查询错了?
INSERT INTO frui
你必须使用
ALTER TABLE fruit ADD UNIQUE (name)
然后使用
INSERT IGNORE INTO fruit (name) VALUES ('mango')