如何从不适合某些条件的表中删除行

时间:2013-02-21 18:04:48

标签: mysql duplicate-removal delete-row

到目前为止,我遇到了一个无法找到答案的问题。

我有一张这样的表:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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