MySQL加入3个表,包括Count,Group&在哪里/有条款

时间:2017-07-21 16:02:55

标签: mysql group-by left-join

我有3张桌子

TABLE ii_ProductCategory
-------------------
id    title  

TABLE ii_Product2Category
-------------------
categoryId    productId

TABLE ii_Product
----------------
id    minPrice

我想要查找所有类别或者根本不包含在ii_Product2ategory中,或者只链接到minPrice IS为NULL的产品。

这是我的尝试。我收到了GROUP BY ERROR。

SELECT COUNT(DISTINCT p2c.`categoryId`) as "ProdCount",  
    cat.`id`,
    cat.`title`,
    prod.`minPrice`
FROM `ii_ProductCategory` cat  
LEFT JOIN `ii_Product2Category` p2c 
    ON p2c.`categoryId` = cat.`id`
LEFT JOIN `ii_Product` prod
    ON p2c.`productId` = prod.`id`
WHERE prod.`minPrice` IS NULL
    AND COUNT(DISTINCT p2c.`categoryId`) = 0
GROUP BY cat.`id`

我尝试将prod.minPrice IS NULL移动到加入HAVING,但这也不起作用。我还希望能够删除AND COUNT(DISTINCT p2c.categoryId) = 0并按ProdCount排序,这样我就可以看到每个产品的总数是否为空。

1 个答案:

答案 0 :(得分:1)

不对非聚合列进行分组没有意义。

SELECT COUNT(DISTINCT p2c.`categoryId`) as "ProdCount",  
    cat.`id`,
    cat.`title`,
    prod.`minPrice`
FROM `ii_ProductCategory` cat  
LEFT JOIN `ii_Product2Category` p2c 
    ON p2c.`categoryId` = cat.`id`
LEFT JOIN `ii_Product` prod
    ON p2c.`productId` = prod.`id`
WHERE prod.`minPrice` IS NOT NULL
GROUP BY cat.`id`, cat.`title`, prod.`minPrice`
HAVING COUNT(DISTINCT p2c.`categoryId`) = 0