2012-02-25 60 views
1

我需要連接表來進行聚合。我吮吸那個。這是我的場景:與MySQL連接兩個表進行聚合?

CATEGORIES 
CatID | CategoryName | Parent 
1  | Cars   | NULL 
2  | Electronics | NULL 
3  | DVD   | 2 
4  | Blu_ray  | 2 
5  | Shoes  | NULL 

所以基本上,最頂層的元素沒有父母。然後,我有

PRODUCTS 
ProdID | Prod Name  | CatID 
1  | DVD Player 1  | 3 
2  | Blu-Ray Player | 3 
3  | Nike    | 5 
4  | DVD Player 2  | 3 

我想結束了......

CATEGORIES 
CatID | CategoryName | Parent | totalProds 
1  | Cars   | NULL | 0 
2  | Electronics | NULL | 0 
3  | DVD   | 2  | 2 
4  | Blu_ray  | 2  | 1 
5  | Shoes  | NULL | 1 

任何想法?

回答

1

您是不是要求每個類別的產品總數?

SELECT CatID, CategoryName, Parent, COUNT(*) totalProds 
FROM categories c 
INNER JOIN products p ON p.CatID = c.CatID 
GROUP BY CatId 
0

請參見下面的查詢

SELECT 
    c.`CatID`, 
    c.`CategoryName`, 
    c.`Parent`, 
    COALESCE(COUNT(DISTINCT p.`ProdID`),0) AS totalProds 
FROM `CATEGORIES` c 
LEFT JOIN `PRODUCTS` p 
ON p.`CatID` = c.`CatID` 
ORDER BY c.`CatID` 

LEFT JOIN返回一個排的每個類別。 COALESCE以確保在適當的情況下返回0。

0

假設您的類別級別數量有限,則可以一次組合每個級別。下面是4個級別:

SELECT c1.CatID, c1.CategoryName, c1.Parent, COUNT(1) totalProds 
FROM products p 
INNER JOIN categories c1 ON c1.CatID = p.CatID 
GROUP BY c1.CatID, c1.CategoryName, c1.Parent 
UNION 
SELECT c2.CatID, c2.CategoryName, c2.Parent, COUNT(1) 
FROM products p 
INNER JOIN categories c1 ON c1.CatID = p.CatID 
INNER JOIN categories c2 ON c2.CatID = c1.Parent 
GROUP BY c2.CatID, c2.CategoryName, c2.Parent 
UNION 
SELECT c3.CatID, c3.CategoryName, c3.Parent, COUNT(1) 
FROM products p 
INNER JOIN categories c1 ON c1.CatID = p.CatID 
INNER JOIN categories c2 ON c2.CatID = c1.Parent 
INNER JOIN categories c3 ON c3.CatID = c2.Parent 
GROUP BY c3.CatID, c3.CategoryName, c3.Parent 
UNION 
SELECT c4.CatID, c4.CategoryName, c4.Parent, COUNT(1) 
FROM products p 
INNER JOIN categories c1 ON c1.CatID = p.CatID 
INNER JOIN categories c2 ON c2.CatID = c1.Parent 
INNER JOIN categories c3 ON c3.CatID = c2.Parent 
INNER JOIN categories c4 ON c4.CatID = c3.Parent 
GROUP BY c4.CatID, c4.CategoryName, c4.Parent 

希望你的想法...