简体   繁体   English

仅统计与SQL一对多关系的子记录条数

[英]Counting the number of child records in a one-to-many relationship with SQL only

I have a database with two tables: data and file .我有一个包含两个表的数据库: datafile

file_id is a foreign key from data to file . file_id是从datafile的外键。 So, the relationship from data to file is n to one.因此,从datafile的关系是 n 对一的。

Is there a way with using SQL only to find out how many records of data refer to each record of file ?有没有办法只使用 SQL 来找出有多少data记录引用每个file记录?

For example, I can find how many records of data are referring to file with id 13:例如,我可以找到有多少数据记录引用了 ID 为 13 的文件:

select count(*) from data where file_id = 13;

I want to know this for every file_id.我想知道每个 file_id。 I tried the following command to achive this, but it gives the count for all file_id records:我尝试了以下命令来实现此目的,但它给出了所有 file_id 记录的计数:

mysql> select distinct file_id, count(*) from data where file_id in (select id from file);
+---------+----------+
| file_id | count(*) |
+---------+----------+
|       9 |     3510 |
+---------+----------+

Distinct returns distinct values per row, not per some group. Distinct 每行返回不同的值,而不是每个组。 MySql allows for use of aggregate functions without a group by, which is totally misleading. MySql 允许在没有分组依据的情况下使用聚合函数,这完全是误导。 In this case you got a random file_id and a count of all records - certainly something you did not intend to do.在这种情况下,您得到了一个随机的 file_id 和所有记录的计数——当然这是您不打算做的。

To get group count (or any other aggregate function), use group by clause:要获取组计数(或任何其他聚合函数),请使用 group by 子句:

select file_id, count(*)
  from data
 group by file_id

GROUP BY...通过...分组...

SELECT file_id, COUNT(*)
  FROM data
 GROUP BY file_id
select file_id, count(*)
  from data
 group by file_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM