Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 |
+---------+----------+
like image 264
Mert Nuhoglu Avatar asked Apr 08 '12 16:04

Mert Nuhoglu


3 Answers

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
like image 90
Nikola Markovinović Avatar answered Oct 02 '22 00:10

Nikola Markovinović


GROUP BY...

SELECT file_id, COUNT(*)
  FROM data
 GROUP BY file_id
like image 43
Jonathan Leffler Avatar answered Oct 02 '22 02:10

Jonathan Leffler


select file_id, count(*)
  from data
 group by file_id
like image 23
Trevor North Avatar answered Oct 02 '22 00:10

Trevor North