MySQL 如果项目不存在,则仅插入到表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20928181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Only insert into table if item does not exist
提问by izolate
My database has a table called fruit
:
我的数据库有一个名为fruit
:
Table fruit
桌子 fruit
+-------------+
| id | name |
+ ----------- +
| 1 | apple |
| 2 | orange |
| 3 | banana |
| 4 | grape |
+-------------+
id
is the a primary key. I want to add entries to the table, but only if they don't exist already.
id
是主键。我想向表中添加条目,但前提是它们不存在。
The query
查询
IF NOT EXISTS (SELECT name FROM fruit WHERE name = 'mango')
INSERT INTO fruit (name)
VALUES ('mango')
Error
错误
I use a SQL GUI app called Sequel Pro, and this query errors with the following:
我使用名为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
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
Perhaps
也许
Something fishy may be going on. The query may be stopping at INSERT INTO frui
. Problem with the app? Or is my query wrong?
可能正在发生一些可疑的事情。查询可能在 停止INSERT INTO frui
。应用程序有问题?还是我的查询错了?
回答by ShiningLight
You'd have to use
你必须使用
ALTER TABLE fruit ADD UNIQUE (name)
and then use
然后使用
INSERT IGNORE INTO fruit (name) VALUES ('mango')