2010-12-21 99 views
1

我有一个表像MySQL的自动防止重复插入

create table adjacencies(
    relationId int not null primary key auto_increment, 
    parent int not null, 
    child int not null, 
    pathLen int not null 
) ; 

我将大量条目像

insert into adjacencies(parent, child, pathLen) 
select a, b, c from something where condition ; 

所以有时候,当我跑我的插入查询,它可能是一个(父母,孩子)关系已经存在并被复制。坏消息。

我不想在(父,子)上创建主键,因为这会导致硬失败(查询失败)。

我要的是一个软故障如果试图插入(父母,子女)已经存在于表中对(即只对被忽略和查询所得的剩余一般)。

在MySQL中这样做的最好方法是什么?

(*想知道why is there a relationId member in this table?

回答

1

创建周围的家长和孩子列的组合唯一关键。然后发出这样的查询,而不是:

insert ignore into adjacencies(parent, child, pathLen) 
select a, b, c from something where condition ; 

IGNORE条款将变成重复键错误到警告。

+0

我速度更快,但仍然没有任何upvotes:' - (** UPD **:领带在这种情况下很好:-) – zerkms 2010-12-21 03:14:23

1

使用

INSERT IGNORE ... 

,并创建唯一索引/主键

如果使用IGNORE关键词,在执行INSERT语句中出现的错误而不是作为警告。例如,如果没有IGNORE,表中重复表中现有UNIQUE索引或PRIMARY KEY值的行会导致重复键错误,并且语句会中止。使用IGNORE时,该行仍未插入,但未发出错误。

(C)http://dev.mysql.com/doc/refman/5.1/en/insert.html