[英]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.