0

我想我只是没有看到所有树木中的森林......

a) 两个表:

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

b)我想要一个查询,显示每个用户进行了多少购买..

c)这个查询:

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

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

非常感谢提前

4

2 回答 2

3
SELECT u.ID, 
       u.UserName, 
       (SELECT COUNT(1) FROM Purchases p WHERE u.Id=p.User_Id) AS Purchases
FROM User u
于 2012-11-14T07:46:48.657 回答
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
于 2012-11-14T07:42:29.517 回答