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.
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.
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 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.