一对多关系查询与计数

时间:2014-11-16 00:46:07

标签: mysql sql

我有以下查询:

this->getDoctrine()->getManager();
        $sql = "SELECT shop.*
                FROM instagram_shop shop
                LEFT JOIN instagram_shop_picture picture 
                ON picture.shop_id = shop.id
                WHERE COUNT(picture) = 0
                AND shop.isLocked = 0
                AND shop.expirydate IS NOT NULL 
                AND shop.expirydate > now()
                AND shop.deletedAt IS NULL
                "

想要所有拥有0张照片的商店。但是这会返回一个sql错误:

General error: 1111 Invalid use of group function

为什么会这样?

3 个答案:

答案 0 :(得分:2)

SELECT shop.id
FROM instagram_shop shop
LEFT JOIN instagram_shop_picture picture ON picture.shop_id = shop.id
WHERE shop.isLocked = 0
AND shop.expirydate IS NOT NULL 
AND shop.expirydate > now()
AND shop.deletedAt IS NULL
GROUP BY shop.id
HAVING COUNT(picture.shop_id) = 0

答案 1 :(得分:1)

如果没有 group bycount(),您可以执行所需的操作。只需找到left join失败的地方:

SELECT shop.*
FROM instagram_shop shop LEFT JOIN
     instagram_shop_picture picture 
     ON picture.shop_id = shop.id
WHERE picture.shop_id is NULL AND
      shop.isLocked = 0 AND
      shop.expirydate IS NOT NULL AND
      shop.expirydate > now() AND
      shop.deletedAt IS NULL

答案 2 :(得分:0)

不知道我猜你会缺少的架构

GROUP BY shop.id

在查询结束时。

还有

HAVING COUNT(picture) = 0