mysql count,distinct,join?混乱

时间:2010-04-18 15:15:53

标签: mysql join count

我有两张桌子:

tblItems 
ID           |     orderID             | productID
1                   1                     2
2                   1                     2
3                   2                     1
4                   3                     2

tblProducts
productID    |     productName
1                   ABC
2                   DEF

我试图根据“tblItems”中的whats找到最受欢迎的产品,并显示产品名称及其在tblItems表中出现的次数。

我可以让mysql计算总数,如:

$ sql =“SELECT COUNT(productID)AS CountProductID FROM tblItems”;

但我无法弄清楚如何加入产品表...如果我尝试LEFT JOIN查询可怕的错误

希望这不会太令人困惑..谢谢

3 个答案:

答案 0 :(得分:1)

您是否只是想按产品查找订单数量:

Select P.ProductName, Count(*)
From tblItems As I
    Join tblProducts As P
        On P.ProductId = I.ProductId
Group By P.ProductName

答案 1 :(得分:0)

我想你可能正在寻找类似的东西:

SELECT tblProducts.productName, COUNT(tblItems.ID)
FROM tblProducts
LEFT JOIN tblItems USING(productID)
GROUP BY tblProducts.productID

答案 2 :(得分:0)

SELECT count(i.productID) AS cnt, p.productName FROM tblItems AS i
LEFT JOIN tblProducts AS p ON p.productID = i.productID
GROUP BY i.productID
ORDER BY cnt desc