我有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排序,这样我就可以看到每个产品的总数是否为空。
答案 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