tags:

views:

53

answers:

2

I have to tables, users and classes. I need to show the classes count of each user with user ID and i have to show those users as well .. with no classes. how to do it ..

+2  A: 
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
Dex
OMG Ponies
thanks .. .. ..
alee
A: 

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
staticbeast
It's equivalent to the LEFT JOIN in Dex's answer, though Dex's is more liable to be efficient depending on the optimizer
OMG Ponies
You're right, I didn't follow through the logic of the left outer join returning the multiple rows to count, rookie mistake on my part. For some reason I thought it would return users per Class, which it won't.
staticbeast