简体   繁体   中英

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 .

file_id is a foreign key from data to file . So, the relationship from data to file is n to one.

Is there a way with using SQL only to find out how many records of data refer to each record of file ?

For example, I can find how many records of data are referring to file with id 13:

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

I want to know this for every file_id. I tried the following command to achive this, but it gives the count for all file_id records:

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. MySql allows for use of aggregate functions without a group by, which is totally misleading. In this case you got a random file_id and a count of all records - certainly something you did not intend to do.

To get group count (or any other aggregate function), use group by clause:

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

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.

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