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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With