2010-12-13 86 views
0

我有4个表多台MySQL查询

Table: Category 
    CategoryID (int) 
    Name (varchar) 
Table: Products 
    ProductID (int) 
    CategoryID (int) 
    Name (varchar) 
    Description (text) 
Table: Sales 
    SalesID (int) 
    ProductID (int) 
Table: Links 
    LinkID (int) 
    ProductID (int) 

现在我需要显示的数据为:我怎样才能做到这一点

CategoryName  Total Products  Total Sales  Total Links 
    ABC    5     12   50 
    XYZ    12     26   10 

,可在单个查询

帮助赞赏

谢谢

回答

0
SELECT CategoryName, Count(distinct p.ProductId) TotalProducts, Count(distinct s.SalesId) TotalSales, 
     COUNT(distinct l.LinkId) TotalLinks 
    FROM Products p JOIN SALES s on p.ProductId = s.ProductId 
     JOIN Categories c ON c.CategoryId = p.CategoryId 
     JOIN Links l ON p.ProductId = l.LinkId 
    GROUP BY CategoryName 
+0

如果某个类别没有任何销售,这将不会返回行。通常你会想要显示每个类别,特别是如果它包含产品,在给定的时间段内它是否有销售。 – GolezTrol 2010-12-13 09:01:05

+0

你给了一个很好的工作解决方案,谢谢 – 2010-12-13 09:18:31

+0

@GolezTrol,你是对的 - 但没有在OP中找到这个要求,在这种情况下从JOIN变为LEFT JOIN帮助。 (当然Count(..)应该改为跟踪NULL值) – 2010-12-13 09:19:36

0
SELECT 
     CAT.Name CategoryName, 
     (SELECT COUNT(P.ProductsID) FROM Products P WHERE P.CategoryID=CAT.CategoryID) TotalProducts, 
     (SELECT COUNT(S.SalesID) FROM Sales S JOIN Products P ON S.ProductID=P.ProductID WHERE P.CategoryID=CAT.CategoryID) TotalSales, 
     (SELECT COUNT(L.LinkID) FROM Links L JOIN Products P ON L.ProductID=P.ProductID WHERE P.CategoryID=CAT.CategoryID) TotalLinks 
FROM 
     CATEGORY CAT 
+1

不要使用count(*)。 *会使MySQL更多地获取比需要的更多的字段,并且如果您的表中有一些大型字段(如备忘录),则可能会显着降低性能。 – GolezTrol 2010-12-13 08:58:59

+0

@GolezTrol:谢谢。 – CristiC 2010-12-13 09:23:43

0
select 
    c.CategoryId, 
    c.name as CategoryName, 
    count(p.ProductId) as TotalProducts, 
    (select count(s.salesid) from sales s where s.ProductId = p.ProductId) as TotalSales, 
    (select count(l.linkid) from products l where l.ProductId = p.ProductId) as TotalLinks 
from 
    Category c 
    left join Products p on p.CategoryId = c.CategoryId 
group by 
    c.CategoryId, 
    c.Name