1. 程式人生 > >mysql自連線實現刪除問題

mysql自連線實現刪除問題

 

現有如下需求

               如圖所示:對於同一code-color欄位分組下得資料,如果date2等於date1,那麼就刪除這兩條資料,如果有連續得三條這種資料就刪除連續得三條。

               具體實現思路,先採用自連線處理,這樣會有滿足條件得資料的id欄位,這兩條資料的id自連線後分別處於一條資料的兩個不同欄位中,在對這兩個欄位用union進行求並集(去重),最後通過ID進行刪除。

               sql如下:

               DELETE from taopai WHERE id in (SELECT t1.id1 id FROM (SELECT t1.id id1,t2.id id2 from taopai t1,taopai t2 WHERE t1.`code-color`=t2.`code-color` and t2.date2=t1.date1) t1 UNION SELECT t2.id2 id from (SELECT t1.id id1,t2.id id2 from taopai t1,taopai t2 WHERE t1.`code-color`=t2.`code-color` and t2.date2=t1.date1) t2);