用MySQL连接两个表进行聚合?

时间:2012-02-25 01:32:44

标签: 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

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您是不是只询问每个类别的产品总数?

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

答案 1 :(得分: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。

答案 2 :(得分: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

希望你能得到这个想法......