简单数据库查询

时间:2010-06-26 00:42:40

标签: sql

我有两个表,用户和类。我需要显示具有用户ID的每个用户的类计数,我还必须显示这些用户..没有类。怎么做..

3 个答案:

答案 0 :(得分:2)

SELECT Users.id, Users.username, COUNT(*) AS classes 
  FROM Users 
LEFT OUTER JOIN Classes ON User.fk_class_id = Classes.id 
       GROUP BY Users.id, Users.username

答案 1 :(得分:0)

我认为一个子选择可能是实现这一目标的最简单方法。

SELECT U.id, numClasses = (SELECT COUNT(1) FROM classes WHERE userID = U.id)
  FROM Users U

答案 2 :(得分:0)

select a.user_name, a.user_id, count(b.class_name)
from user as a
left join class as b
on a.class_id = b.id