我正在將一些數據從csv文件導入到MySQL並試圖忽略重複的行。忽略重複的行
mysql_query("INSERT IGNORE INTO products (parent_product_url, child_product_url, swatch) VALUES ('".$row[0]."', '".$row[1]."', '".$row[2]."')");
我的csv文件。
polo.htm,red.htm,red.jpg
polo.htm,green.htm,green.jpg
round-neck.htm,green.htm,green.jpg
現在,如果我運行下面的csv文件,因爲他們已經在表中存在,它應該忽略前三行。它應該只插入第四行。
polo.htm,red.htm,red.jpg
polo.htm,green.htm,green.jpg
round-neck.htm,green.htm,green.jpg
v-neck.htm,red.htm,red.jpg
什麼是產品的主鍵,你有什麼獨特的鍵也? – zedfoxus
ID是主鍵,它具有自動增量功能,我沒有唯一鍵,但我認爲我們可以將「child_product_url」視爲唯一鍵。 – AZee
好的,在這種情況下,MySQL的行爲是正確的。如果該記錄違反主鍵或唯一鍵,'insert ignore'將會引發警告並且不插入記錄。由於這三個字段的組合並沒有違反任何約束,所以MySQL樂於重複地插入這些數據。爲了防止這種情況發生,您可以在parent_product_url上創建唯一的索引(如果這樣做有意義)。 – zedfoxus