简体   繁体   English

如何使用MySQL子查询计算外部表中的行数?

[英]How do I use a MySQL subquery to count the number of rows in a foreign table?

I have two tables, users and reports . 我有两个表, usersreports 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.

相关问题 如何计算MySQL表中的行数? - How do I count the number of rows in a MySQL Table? 如何计算返回的行数? - How do I count the number of rows returned? 如何在yii中使用ajax / jquery将行添加到另一个表中并将这些值用作表单中的外键? - How do I use ajax/jquery in yii to add rows to another table and use these values as foreign key in a form? 如何计算 MySQL 表中的行数 (PHP PDO) - How to count number of rows in MySQL table (PHP PDO) 如何计算mysql中的行数? - How to count number of rows in mysql? 如何从表中获取行数并插入MySQL的同一表中? - How do I get the number of rows from a table and insert into the same table in MySQL? 我如何需要返回查询以计算行数,以及如何计算行数? - How do I need to return the query in order to count the number of rows, and how do I count the rows? 如何在有条件的情况下计算第二张表中的外键数量并在第一张表中的行中显示它-PHP-MySQL - How to calculate number of foreign keys in second table with a condition and display it with rows from first table - PHP - MySQL? 如何将通过外键连接的两个表中的所有行迭代到 PHP、CodeIgniter、MySQL 中的单个表中 - How do I iterate all rows from two tables connected by foreign key into a single table in PHP, CodeIgniter, MySQL 如何将行数可变的表单中的数据添加到MySQL表中? - How do I add data from a form with a variable number of rows into a MySQL table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM