[英]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'.学生只能在 1 个俱乐部中,因此 clubID 是“学生”中的外键。
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您需要使用clubs.clubName, clubs.clubDescription
列添加group by clause
,因为count()
是一个聚合函数
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.