简体   繁体   English

一对多关系查询

[英]one to many relationship query with count

I have the following query: 我有以下查询:

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
                "

Wanted to get all shops that has 0 pictures in it. 想要获得所有带有0张图片的商店。 But this returns a sql error of: 但这会返回以下SQL错误:

General error: 1111 Invalid use of group function

Why is this? 为什么是这样?

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

You can do what you want without a group by or count() . 您可以在没有 group bycount() Just find the places where the left join fails: 只需找到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

Not knowing the schema I would guess you are missing 不知道架构,我想你会丢失

GROUP BY shop.id

at then end of the query. 在查询结束时。

Also with having 也有

HAVING COUNT(picture) = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM