Mysql ONLY_FULL_GROUP_BY + Join + GroupBy + Count =无效计数

时间:2017-02-02 16:19:51

标签: mysql sql select group-by left-join

我正在尝试运行查询:

SELECT cc.slug AS cc_slug
     , cp.slug AS cp_slug
     , COUNT(cp.id) 
  FROM catalog_categories AS cc 
  LEFT 
  JOIN catalog_products cp 
    ON cc.id = cp.category_id 
 GROUP 
    BY cc.id
     , cp.id

并希望获得每个类别的相关产品数量,但我只检索“0”和“1”而不是正确的计数。它是由第二个分组group by ... cp.id引起的,但是由于ONLY_FULL_GROUP_BY已启用,因此无法将其删除。因此,例如,如果我运行查询(没有按联合表分组):

SELECT COUNT(cp.id) 
  FROM catalog_categories AS cc 
  LEFT 
  JOIN catalog_products cp 
    ON cc.id = cp.category_id 
 GROUP 
    BY cc.id

我得到了正确的结果,但问题是我在SELECT中需要所有这些字段和别名。

有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您可以将cp.id放在这样的聚合函数中:

SELECT COUNT(cp.id), MAX(cp.id) 
FROM catalog_categories AS cc 
LEFT JOIN catalog_products cp ON cc.id = cp.category_id 
GROUP BY cc.id

这样您就可以选择cp.idcc.idNetwork

答案 1 :(得分:1)

我认为这就是你想要的:

SELECT cc.slug AS cc_slug, cp.slug AS cp_slug, COUNT(cp.id)
FROM catalog_categories cc LEFT JOIN
     catalog_products cp
     ON cc.id = cp.category_id
GROUP BY cc.slug, cp.slug;

非汇总列应位于GROUP BY

编辑:

这是你想要的吗?

SELECT cc.slug AS cc_slug, COUNT(cp.id)
FROM catalog_categories cc LEFT JOIN
     catalog_products cp
     ON cc.id = cp.category_id
GROUP BY cc.slug;