2013-09-05 54 views
1

我試圖從一個數據集中刪除整個數據集,當其中一個重排(請參閱下面的示例數據)滿足最低要求(x < 15)時。MySQL專門刪除條件

+------+-------+------------+----+ 
| id | block | repitition | x | 
+------+-------+------------+----+ 
| 5223 | 1  | 1   | 15 | 
| 5223 | 1  | 2   | 17 | 
| 5223 | 1  | 3   | 16 | 
| 5223 | 2  | 1   | 14 | 
| 5223 | 2  | 2   | 15 | 
| 6238 | 2  | 1   | 18 | 
| 6238 | 2  | 2   | 20 | 
| 6238 | 2  | 3   | 12 | 
| 6238 | 2  | 4   | 21 | 
| 7575 | 1  | 3   | 13 | 
| 7575 | 1  | 4   | 21 | 
| 7575 | 1  | 5   | 21 | 
+------+-------+------------+----+ 

我被扶在這方面已經有以下幾點:

delete t1 
from your_table t1 
inner join 
(
    select id, block 
    from your_table 
    group by id, block 
    having sum(x < 15) > 0 
) t2 on t1.id = t2.id and t1.block = t2.block 

這完美的作品。我想知道的是,如果我可以做到完全一樣,但只有在一個塊中的第一個重複 - 不管重複次數如何。

因此,我想查詢該表並讓它只刪除行4,5,10,11,12的電流式也將刪除行6,7,8,和9

回答

0
delete t4 
from your_table t4 
inner join 
    (select id,block From YourTable t1 
    inner join 
    ( 
     select id,block,min(repitition) as FirstRepitition 
     From YourTable Group By id,Block 
    ) t2 
    On t1.id = t2.id and t1.block = t2.block 
    and t1.Repitition = t2.FirstRepition and t1.x < 15 
) t3 
    On t4.id = t3.id and t4.block = t3.block 

將是一種方式。找到最早的重複,得到其中的x,然後刪除很多。凌亂,但...

+0

非常感謝你託尼霍普金森!太棒了! – wernerbrand