2010-12-13 85 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