查询以找到在软删除中删除所有图片的商店

时间:2015-06-09 23:07:10

标签: mysql sql

我大致有以下查询:

SELECT s.username
FROM  `instagram_shop` s
INNER JOIN  `instagram_shop_picture` 
p ON s.id = p.shop_id
WHERE s.deletedAt IS NULL 
AND p.deletedAt IS NOT NULL 
GROUP BY s.id
HAVING COUNT( p.id ) = NUMBER_OF_TOTAL_PICTURES_IN_SHOP_S

我正在努力寻找商店所有它的照片都被删除了。意味着删除了所有图片的商店,我该怎么办?

我已经尝试过制作它,但是我对如何找到商店的照片总数感到困惑。

我尝试了以下但是它不起作用:

SELECT s.username
FROM  `instagram_shop` s
INNER JOIN  `instagram_shop_picture` p ON s.id = p.shop_id
WHERE s.deletedAt IS NULL 
AND p.deletedAt IS NOT NULL 
GROUP BY s.id
HAVING COUNT( p.id ) = COUNT(SELECT pp.id FROM `instagram_shop_picture pp` WHERE pp.shop_id = s.id) 

我相信你做完后不能做计数。

1 个答案:

答案 0 :(得分:0)

  

我相信在COUNT之后你无法HAVING

但是你可以之前执行COUNT,包括查询中的结果,并运行外部查询来过滤掉计数。您可以在外部查询中使用HAVING或使用WHERE

SELECT b.id, b.username FROM (
    SELECT
        s.id,
        s.username,
        COUNT(*) AS Total,
        SUM(IF(p.deletedAt IS NOT NULL, 1, 0)) AS SoftDeleted
    FROM  `instagram_shop` s 
    JOIN  `instagram_shop_picture` p
    ON (s.id = p.shop_id)
    WHERE s.deletedAt IS NULL
    GROUP BY s.id, s.username
) AS b;

您可以find a SQL Fiddle演示该方法(内部查询)。

SELECT商店将所有图片软删除,并取消删除

要做到这一点,我们需要处于此状态的商店,然后是图片

UPDATE `instagram_shop_picture` u
JOIN ( above query retrieving emptied shops' with their ids ) AS d
  ON ( u.shop_id = d.id )
SET deletedAt = NULL;

几乎等效

UPDATE `instagram_shop_picture` SET deletedAt = NULL
WHERE shop_id IN ( similar query retrieving only shops' ids );

几乎因为第二种语法需要一个只返回id的查询,而第一个版本可以不删除额外的字段。

UPDATE `instagram_shop_picture` u
JOIN ( 

    SELECT
        s.id,
        s.username,
        SUM(1) AS Total,
        SUM(IF(p.deletedAt IS NOT NULL, 1, 0)) AS SoftDeleted
    FROM  `instagram_shop` s 
    JOIN  `instagram_shop_picture` p
       ON (s.id = p.shop_id)
    WHERE s.deletedAt IS NULL
    GROUP BY s.id, s.username

) AS d
  ON ( u.shop_id = d.id )
SET deletedAt = NULL;

对于第二个版本,我们需要一个外部查询删除我们不需要的字段,一旦他们完成了他们要做的事情:

SELECT b.id, b.username FROM (

    SELECT
        s.id,
        s.username,
        SUM(1) AS Total,
        SUM(IF(p.deletedAt IS NOT NULL, 1, 0)) AS SoftDeleted
    FROM  `instagram_shop` s 
    JOIN  `instagram_shop_picture` p
       ON (s.id = p.shop_id)
    WHERE s.deletedAt IS NULL
    GROUP BY s.id, s.username

) AS b;

在这种情况下,外部查询不是非常昂贵,它充当内部查询的一种过滤器。在某些情况下,我发现它可以提示优化器更改其索引选择, 可能会产生不良后果。人们可以诉诸index hinting来解决这个问题。

与所有"大规模更新"查询,在预生产中对此进行测试首先备份您的数据