当主键自动递增时,在MySql中插入Ignore

时间:2013-06-22 10:24:09

标签: mysql sql

如果有一列primary keyauto increments的列,我怎么能在Mysql中使用insert ignore。

primary keys id(主键自动增量),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吗?

1 个答案:

答案 0 :(得分:3)

为了让INSERT IGNORE适用于您的情况,您需要在(userId, elmCol)上创建一个独特的索引。

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

这是 SQLFiddle 演示。

相关问题