如何使用 MySQL 子查询来计算外表中的行数?
我有两个表,users
和 reports
。每个用户都没有与其关联的一个或多个报告,并且 reports
表有一个 user_id
字段。
我有以下查询,我需要向每一行添加用户拥有多少个报告的计数:
SELECT *
FROM users
LIMIT 1, 10
我是否需要使用子查询,如果需要,如何有效地使用它? reports
表有成千上万行。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不需要子查询:
为了使查询更高效,请确保两个表中的 user_id 字段都有索引注释
后续:COUNT 函数不计算空值,因此对于任何具有空值的用户,它将返回 0(如预期)根本没有报告(连接将为reports.user_id返回NULL)。还添加了 GROUP BY 位,第一次忘记了。
There's no need for a subquery:
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.
您可能需要将 IF() 更改为
you might need to change the IF() to