[英]How to count from two table using JOIN and GROUP BY
我是一個新手,在這種情況下,我有兩個桌子
類別-CatId-CatName
產品-ProductId-CatId-ProductName
我想使用此查詢顯示帶有計數產品和即時通訊的類別時,計算類別中有多少產品
SELECT * , COUNT(Product.ProductId) AS NumberProducts FROM Category
JOIN Product
ON Category.CatId = Product.CatId
GROUP BY Product.CatId
如果我有產品存在表Product中的catid,此查詢就可以正常工作,如果不是我的類別不會顯示在類別列表中,則類別將消失。
請幫忙。 提前致謝
SELECT * , COUNT(Product.ProductId) AS NumberProducts FROM Category
LEFT JOIN Product
ON Category.CatId = Product.CatId
GROUP BY Product.CatId
左聯接應該可以解決問題
選擇*是問題所在-您正在尋找類別和產品數量的列表。
您會得到您所要的。 (c和p是使SQL更具可讀性的別名)
SELECT c.*, COUNT(p.ProductId) AS NumberProducts FROM Category as c
LEFT JOIN Product as p
ON c.CatId = p.CatId
GROUP BY c.CatId
產生
CatId CategoryName NumberProducts
1 T-Shirts 2
2 Sneakers 0
3 Boots 0
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.