从MySQL中删除COUNT(*)

时间:2012-05-11 15:46:02

标签: mysql count sql-delete having

好的,所以这里已经有几个帖子,网上还有更少的帖子。我真的尝试了每一个,无法得到任何工作。希望有人在这里可以怜悯我:)。

这是我正在使用的数据。我想删除所有这些记录。

SELECT
part_desc, count(*) as rec_num
FROM ag_master
GROUP BY part_desc HAVING COUNT(*) > 1000;

+--------------------------------------+---------+
| part_desc                            | rec_num |
+--------------------------------------+---------+
| SILICON DELAY LINE, TRUE OUTPUT      |    1092 |
| LOADABLE PLD                         |    1401 |
| 8-BIT, FLASH, 8 MHz, MICROCONTROLLER |    1411 |
| FPGA                                 |    1997 |
| 8-BIT, MROM, 8 MHz, MICROCONTROLLER  |    3425 |
+--------------------------------------+---------+
5 rows in set (0.00 sec)

我最接近找到可以执行此操作的代码如下所示。语法检查正常并运行,但它似乎只是挂起数据库。我让它运行了长达10分钟,没有任何事情发生,所以我放弃它。

DELETE
FROM ag_master
WHERE part_id IN (
  SELECT part_id
  FROM ag_master
  GROUP BY part_desc
  HAVING COUNT(*) > 1000
);

这是关于tmp表的解释计划

mysql> EXPLAIN SELECT * FROM ag_master WHERE part_desc IN (SELECT part_desc FROM tmp);
+----+--------------------+-----------+--------+---------------+------+---------+------+--------+-------------+
| id | select_type        | table     | type   | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+--------------------+-----------+--------+---------------+------+---------+------+--------+-------------+
|  1 | PRIMARY            | ag_master | ALL    | NULL          | NULL | NULL    | NULL | 177266 | Using where |
|  2 | DEPENDENT SUBQUERY | tmp       | system | NULL          | NULL | NULL    | NULL |      1 |             |
+----+--------------------+-----------+--------+---------------+------+---------+------+--------+-------------+
2 rows in set (0.00 sec)

2 个答案:

答案 0 :(得分:14)

the manual中所述:

  

目前,您无法从表中删除并从子查询中的同一个表中进行选择。

我认为您必须通过临时表执行此操作:

CREATE TEMPORARY TABLE temp
  SELECT   part_desc
  FROM     ag_master
  GROUP BY part_desc
  HAVING   COUNT(*) > 1000;

DELETE FROM ag_master WHERE part_desc IN (SELECT part_desc FROM temp);

DROP TEMPORARY TABLE temp;

答案 1 :(得分:8)

另一种选择是使用内部联接来过滤结果:

DELETE
    ag_master.*
FROM
    ag_master 

    INNER JOIN 
    (
        SELECT 
            part_id
        FROM 
            ag_master
        GROUP BY 
            part_desc
        HAVING COUNT(*) > 1000
    )AS todelete ON
            todelete.part_id = ag_master.part_id