2013-06-22 81 views
0

如果有一列是primary key,那么我如何在Mysql中使用插入忽略以及auto increments当主键自动增量时,在MySql中插入忽略

primary keysid(主键自动递增),和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

+2

表中只能有一个主键,尽管它可以是字段的组合,所以您需要说明您的设置是什么。而“插入忽略”是什么意思? –

回答

3

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

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

这里是SQLFiddle演示。

+0

谢谢......完美地工作。现在:) – Norman

+0

太棒了!我很高兴我可以帮助:)。 – peterm