2013-02-21 90 views
1

我遇到了一個問題,至今我找不到答案。如何從不符合某些條件的表中移除行

我有這樣的一個表:

column1 | column2 | column3 
--------------------------- 
name1 | 3  | 12 
name1 | 3  | 10 
name1 | 2  | 17 
name2 | 3  | 15 
name2 | 3  | 15 
name2 | 2  | 11 

如何刪除行,這已經不在column2和欄3的最高值,(Column2優先)?

結果應該是這樣的:

column1 | column2 | column3 
--------------------------- 
name1 | 3  | 12 
name2 | 3  | 15 
name2 | 3  | 15 
+0

你有什麼試過?我建議你用幾個更簡單的問題來分解你的複雜問題。 – Jocelyn 2013-02-21 18:17:09

+0

我可以通過刪除重複後使用ALTER IGNORE TABLE'table' ADD UNIQUE KEY idx1(column1,column2,column3) - 現在我更新我的第一篇文章 – user2096557 2013-02-21 18:20:17

回答

0

你可以使用這樣的查詢:

DELETE FROM yourtable 
WHERE 
    (column1, column2, column3) NOT IN (
    SELECT * FROM (
     SELECT yourtable.column1, yourtable.column2, max(column3) max_column3 
     FROM 
     yourtable INNER JOIN (
      SELECT column1, max(column2) max_column2 
      FROM  yourtable 
      GROUP BY column1) mx 
     ON yourtable.column1=mx.column1 
      AND yourtable.column2=mx.max_column2 
     GROUP BY 
     yourtable.column1) s 
) 

請參閱小提琴here

+0

這一個完全正常工作。但是,我不確定我是否問過正確的問題。非常感謝 – user2096557 2013-02-25 09:50:18

0

刪除使其混亂,但這些都是要保持的行:

SELECT 
    a.col1, a.col2, b.col3 
FROM 
    (select col1, max(col2) as col2 from table1 group by col1) as a INNER JOIN 
    (select col1, col2, max(col3) as col3 from table1 group by col1, col2) as b 
    ON 
     a.col1 = b.col1 AND a.col2 = b.col2; 

你可以簡單地刪除由@fthiella指出,不在此查詢的行。

看到這個link

+0

我還沒有嘗試過,因爲從fthiella上面的答案工作正常。我會在稍後嘗試,當我有更多時間玩替代品。非常感謝 – user2096557 2013-02-25 09:51:20

相關問題