2015-07-21 72 views
1
What I get     What I need 

id hash assigned  id hash assigned 
-- ---- --------  -- ---- -------- 
1 1j  1    1 1j  1 
2 1j-1 1    3 1j-2 1 
3 1j-2 1    4 3m  1 
4 3m  1    6 3m-8 1 
5 3m-3 1    7 f7  1 
6 3m-8 1    8 6q  0 
7 f7  1    9 3y  0 
8 6q  0    10 3y-3 0 
9 3y  0    
10 3y-3 0    

我的數據集看起來與此類似。散列總是一定的數字,在這種情況下是2個字符。在與順序但不是相同數量單位的擴展同步後修改。我需要刪除這些分配的第一修改1.SQL刪除MIN加上下一最大的一組中

這是我的非工作最好的猜測:

DELETE 
    FROM `table` 
    WHERE (`assigned`=1) 
    IN (SELECT `hash`, min(`hash`)+1 FROM `table` GROUP BY SUBSTRING(`hash`,1 , 2) ORDER BY hash ASC; 
+0

需要你有什麼? – HashSu

+0

哪個數據庫服務器? –

+1

您使用的是什麼RDBMS? – Mureinik

回答

0

你將有字符串比較問題,一旦你的櫃檯進入雙人和三人位。這是一個直截了當的方法,可能會讓你接近。請記住,在實際刪除所有內容之前,嘗試將其作爲select

delete from T 
where 
    assigned = 1 
    -- Business requirement not explained. 
    -- I'm assuming the entire group has the same assigned value. 

    and hash = (
     select min(hash) from T as t2 
      where 
        left(t2.hash, 2) = left(T.hash, 2) 
       and t2.hash > (
        select min(hash) from T as t3 
        where left(t3.hash, 2) = left(t2.hash, 2) 
       ) 
    ) 
+0

這個工作在SELECT很大,但與MySQL中刪除我得到錯誤#1093 - 所以,我修改了它這樣的:DELETE FROM'T' WHERE 'assigned' = 1 和'hash' =( SELECT MIN(' hash')FROM(SELECT * FROM T)爲t2 WHERE LEFT('t2'.'hash',2)= LEFT('T'.'hash',2) 和't2'.'hash'> ( SELECT MIN('hash')FROM(SELECT * FROM'T')作爲't3' WHERE LEFT('t3'.'hash',2)= LEFT('t2'.'hash',2) ) )。這工作。謝謝。我學到了很多。 –

+0

有趣。我並沒有真正使用MySQL,我擔心它不會喜歡某些東西。很高興你找到了解決方法。 – shawnt00

0

SQL服務器

delete from T where id in (
    select 
     t1.id 
    from T t1 
    where t1.assigned = 1 and t1.hash like '%-%' and not exists (
     select * from T t2 where left(t1.hash, 2) = left(t2.hash, 2) and t2.hash like '%-%' and 
      cast(substring(t2.hash, 4, len(t2.hash) - 3) as int) < 
      cast(substring(t1.hash, 4, len(t1.hash) - 3) as int) 
    ) 
)