[英]How do I use a MySQL subquery to count the number of rows in a foreign table?
I have two tables, users
and reports
. 我有两个表,
users
和reports
。 Each user has no, one, or multiple reports associated with it, and the reports
table has a user_id
field. 每个用户都没有关联的一个,一个或多个报告,并且
reports
表具有一个user_id
字段。
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. reports
表有成千上万的行。
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 为了使查询更有效,请确保两个表中的user_id字段都有索引
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). 注释跟进:COUNT函数不计算空值,因此对于所有根本没有报告的用户,它将返回0(按预期)(联接将为report.user_id返回NULL)。 Also added the GROUP BY bit, forgot that the first time around.
还添加了GROUP BY位,忘记了第一次。
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()更改为
IF( Reports.UserID is null, 0, 1 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.