MySQL:SELECT查询,但随后从该查询中删除列相等的记录

时间:2013-08-01 17:51:06

标签: mysql sql database

这是我的初步查询:

SELECT bid_tag.*
FROM bid_tag join
     (select serial_number, count(*) as cnt
      from bid_tag where user_id = 0
      group by serial_number
     ) tsum
     on tsum.serial_number = bid_tag.serial_number and cnt > 1
order by bid_tag.serial_number
LIMIT 0, 21000;

现在从这些结果中,我需要从数据库中选择所有tag_design = 0 AND tag_size = 0然后DELETE那些记录。

我只是不知道如何对初始查询的结果运行查询。

2 个答案:

答案 0 :(得分:2)

只需将SELECT替换为DELETE,它就会删除已选择的行。

DELETE bid_tag.*
FROM bid_tag join
     (select serial_number, count(*) as cnt
      from bid_tag where user_id = 0
      group by serial_number
     ) tsum
     on tsum.serial_number = bid_tag.serial_number and cnt > 1
WHERE tag_design = 0 AND tag_size = 0
order by bid_tag.serial_number
LIMIT 0, 21000;

答案 1 :(得分:0)

在where子句中使用EXISTS术语:

DELETE
  FROM bid_tag btd
 WHERE EXISTS (
           SELECT 1
             FROM (
                     SELECT bid_tag.*
                       FROM bid_tag bts
                       JOIN (
                               SELECT serial_number, count(*) as cnt
                                 FROM bid_tag btj
                                WHERE btj.user_id = 0
                             GROUP BY btj.serial_number
                            ) tsum
                         ON (     tsum.serial_number = bts.serial_number
                              AND tsum.cnt > 1
                            )
                      WHERE bts.tag_design = 0
                        AND bts.tag_size = 0
                   ORDER BY bts.serial_number
                      LIMIT 0
                          , 21000
                  ) rs_base
            WHERE rs_base.id = btd.id   -- PK column
      )
      ;

EXISTS项中的子查询可以进一步嵌套,以包含原始结果集的另一个查询。只需确保始终选择要执行删除的表的主键。

请注意,您可能不希望在删除操作中将自己局限于结果集的一部分,因此请检查是否需要限制前21000个结果 - 如果不这样做,请删除'ORDER BY'和' LIMIT'条款。