简体   繁体   中英

Can I select the count of rows in another table that have the same value as the FK in that table?

Sorry If that's terrible phrasing. Basically I need to make a query that tells me the club name and description from 'clubs', with the total number of students in that club. Students can only be in 1 club so clubID is a Foreign key in 'students'.

I tried to use the below, but quickly learned I'm nowhere near the answer. Is this possible?

SELECT clubs.clubName, clubs.clubDescription, COUNT(students.studentID) 
FROM club JOIN students ON students.clubID = clubs.clubID

You need to add group by clause with clubs.clubName, clubs.clubDescription columns as count() is an aggregate function

SELECT clubs.clubName, clubs.clubDescription, COUNT(students.studentID) 
FROM club JOIN students ON students.clubID = clubs.clubID
group by clubs.clubName, clubs.clubDescription

If you want to include clubs that have no students, you want an outer join or correlated subquery:

select c.*,
       (select count(*) from students s where s.clubID = c.clubId) as num_students
from clubs c;

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