根据属性计数从表中删除

时间:2013-01-16 15:19:47

标签: mysql sql sql-delete

假设我在表x中有一个名为source的列。个别条目可以像;

Id   c1   c2      source ...
1    a     b      something
2    b     a      something  
3    a     b      somethingelse
4    c     a      somethingelse
5    a     b      something
6    b     c      something

如何在源中删除少于3个相同元素的条目?例如,由于源值 somethingelse 出现2次,我需要删除 somethingelse 的所有条目。

4 个答案:

答案 0 :(得分:4)

DELETE  a
FROM    tableName a
        INNER JOIN
        (
            SELECT  source
            FROM    tableName
            GROUP BY SOURCE
            HAVING COUNT(*) < 3
        ) b ON a.source = b.source

要提高性能,还需要做另外一件事,向列SOURCE添加一个INDEX

答案 1 :(得分:0)

大致这样的事情可以胜任

DELETE FROM TABLE_T1 WHERE ID IN (
   SELECT ID FROM TABLE_T1 GROUP BY SOURCE HAVING COUNT(*) < 3
)

答案 2 :(得分:0)

DELETE  id
FROM    yourtable a
JOIN    (
        SELECT  *
        FROM    yourtable
        GROUP BY
                source
        HAVING  COUNT(*) > 3
        ) b
ON      a.id = b.id

答案 3 :(得分:0)

DELETE FROM x WHERE id IN
( SELECT id FROM
  ( SELECT id, COUNT(source) AS n
      FROM x GROUP BY source 
      HAVING n < 3
  )
)