从第二张桌子计算购买量

时间:2012-11-14 07:38:01

标签: mysql sql

我想我只是看不到所有树木的原因......

a)两个表:

  • 用户(ID,用户名,...)
  • 购买(ID,UserID,ItemID,....)

b)我想要一个查询,告诉我每个用户购买了多少次产品。

c)此查询:

SELECT user.*, COUNT(purchases.userid) AS Purchases  
FROM user, purchases  
WHERE user.id=purchases.user_id

只给我一个结果......如果用户没有购买,如何获得0?

提前多多感谢

2 个答案:

答案 0 :(得分:3)

SELECT u.ID, 
       u.UserName, 
       (SELECT COUNT(1) FROM Purchases p WHERE u.Id=p.User_Id) AS Purchases
FROM User u

答案 1 :(得分:1)

尝试这样: -

SELECT user.UserName, ISNULL(COUNT(purchases.userid),0) 
    AS Purchases1 FROM user AS user LEFT JOIN purchases AS purchases
    ON user.id=purchases.user_id
    Group by UserName