开发者

Simple DB query

I have two tables, users and classes. I need to show the classes count of each user开发者_如何学Go with user ID and I have to show those users as well .. with no classes. how to do it ..


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


I think a subselect is probably the easiest way to achieve this.

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜