views:

151

answers:

2

I have two tables, users and reports. Each user has no, one, or multiple reports associated with it, and the reports table has a user_id field.

I have the following query, and I need to add to each row a count of how many reports the user has:

SELECT *
FROM users
LIMIT 1, 10

Do I need to use a subquery, and if so, how can I use it efficently? The reports table has thousands and thousands of rows.

A: 
SELECT users.userid,
       SUM( IF( Reports.userid > 0, 1, 0 )) as TotRpts
   FROM 
       users LEFT JOIN reports
          ON users.userid = reports.userid;
   GROUP BY
       users.userid

you might need to change the IF() to

  IF( Reports.UserID is null, 0, 1 )
DRapp
+1  A: 

There's no need for a subquery:

SELECT users.user_id, COUNT(reports.user_id) AS number_of_reports
FROM users
LEFT JOIN reports ON users.userid = reports.userid
GROUP BY users.user_id

To make the query more efficient, make sure there's indexes on the user_id fields in both tables

comment followup: COUNT function does not count nulls, so it'll return 0 (as expected) for any users which have no reports at all (the join would return a NULL for reports.user_id). Also added the GROUP BY bit, forgot that the first time around.

Marc B
+1 and a comment to make sure this picks up the zero-reports users. Maybe need a statement to present "0" if the reports side offers NULL?
Smandoli