How to count the number of rows in a table using a foreign key in the same query?

Say I have a table1 that contains a field named Name and an ItemID field that is a foreign key for table2.

What I want is a query containing each name, and how many records in table2 have the same ItemID as this record.

How can I do it?

+4
source share
1 answer
select Name, count(ItemID) as itemCount from table1 inner join table2 on table1.ItemID = table2.id group by Name 

but my sql-fu might be rusty: P

Note that this will not give strings for names where table2 does not contain matching strings, so itemCould will always be> 0

+5
source

Source: https://habr.com/ru/post/1340549/


All Articles