[英]SQL: COUNT() with items appearing multiple times in one-to-many relationship? Alternative to GROUP BY?
我有一个查询,其中按超级类别>类别列出了产品类别。 该查询计算每个类别中的产品数量(COUNT(ptc.catid))
。
吼叫声:查询不会让一个类别出现两次(一个类别可以链接到多个超类别)。 如何重写它,以便可以在多个超级类别下列出类别(c.title)?
SELECT
s.supercategory_id,
s.title,
c.title,
c.id,
COUNT(ptc.catid)
FROM supercategories s,
supercategories_to_categories stc,
categories c,
products p,
products_categories ptc
WHERE c.viewable='1'
AND c.id=stc.category_id
AND stc.supercategory_id=s.supercategory_id
AND ptc.catid=c.id
AND ptc.productid = p.id
AND p.viewable='y'
GROUP BY ptc.catid
ORDER BY s.title, c.title
谢谢!
您使用的联接语法有点“老派”,因此,如果您不介意,我会在这里重写它:
select
s.supercategory_id,
max(s.title) as supercategory_title,
max(c.title) as category_title,
c.id,
count(ptc.catid) as product_count
from supercategories s
join supercategories_to_categories stc on stc.supercategory_id = s.supercategory_id
join categories c on c.id = stc.category_id
join products_to_categories ptc on ptc.catid = c.id
join products p on p.id = ptc.productid
where p.viewable = 'y'
group by s.supercategory_id, c.id
如图所示,我已group by
表达式将group by
更改为包括supercategory_id
,从而使一个类别可能会在其所属的每个超级类别中显示一次。 我还围绕非分组依据列添加了聚合函数,因为我不确定该如何执行。
尝试将GROUP BY更改为:
GROUP BY ptc.catid,stc.supercategory_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.