2010-12-21 177 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