【问题标题】:Insert Ignore in MySql when there's primary key that auto increments当存在自动递增的主键时,在 MySql 中插入忽略
【发布时间】:2013-06-22 10:24:09
【问题描述】:

当存在primary keyauto increments 的列时,如何在Mysql 中使用插入忽略。

我在id 上有primary keys(主键自动递增),而userIdelmCol 是没有自动递增的主键。

所以:

id | userId | elmCol
--------------------
 1 | 1     | 1 //Allow
 2 | 1     | 2 //Allow
 3 | 1     | 3 //Allow
 4 | 1     | 1 //Not allowed if inserted again. I've put it in here just for example
 5 | 2     | 1 //Allow
 6 | 2     | 2 //Allow
 7 | 2     | 3 //Allow
 8 | 2     | 1 //Not allowed if inserted again. I've put it in here just for example

我正在使用 MySql 和 MyIsam 类型的表。我可以这样做并使用insert ignore吗?

【问题讨论】:

  • 一个表中只能有一个主键,虽然它可以是字段的组合,所以你需要明确你的设置是什么。 “插入忽略”是什么意思?

标签: mysql sql


【解决方案1】:

为了让INSERT IGNORE 在您的情况下工作,您需要在(userId, elmCol) 上创建一个唯一索引。

ALTER TABLE table_name
ADD CONSTRAINT u_userId_elmCol 
    UNIQUE (userID, elmCol);

这里是 SQLFiddle 演示。

【讨论】:

  • 谢谢...完美运行。现在:)
  • 太棒了!我很高兴能帮上忙 :)。
猜你喜欢
  • 2017-08-03
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 2011-09-11
  • 2014-12-07
  • 1970-01-01
  • 2019-01-09
相关资源
最近更新 更多