【问题标题】:Only insert into table if item does not exist [duplicate]如果项目不存在,则仅插入表中[重复]
【发布时间】:2014-01-22 13:42:11
【问题描述】:

我的数据库有一个名为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 停止。应用程序有问题?还是我的查询有误?

【问题讨论】:

  • 你的方法是错误的。在name 上添加唯一索引,然后使用INSERT IGNORE 并检查插入的行数。
  • @MikeW 你能举例说明如何做到这一点吗?
  • @izolate 好像有人抢了我。

标签: mysql sql insert


【解决方案1】:

你必须使用

ALTER TABLE fruit ADD UNIQUE (name) 

然后使用

INSERT IGNORE INTO fruit (name) VALUES ('mango')

【讨论】:

  • 好的,name 现在是唯一键。并且查询按预期工作。谢谢!
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2019-10-17
  • 2012-12-13
  • 2013-12-22
  • 2011-03-11
  • 1970-01-01
相关资源
最近更新 更多