简体   繁体   English

我可以选择另一个表中与该表中的 FK 具有相同值的行数吗?

[英]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.

相关问题 我怎样才能 select 多行与同一个表中的其他行的计数在一个单独的列中具有它们的主键? - How can I select multiple rows with the count of other rows in the same table that has their primary keys in a separate column? 将多行更新为来自另一个表(FK)的值 - UPDATE multiple rows to Value from another table (FK) Select 具有一个值但没有来自同一个表的另一个值的行 - Select rows that has one value but not another from same table 从一个表中选择结果,并为每一行从另一张表中选择具有相同ID的所有行 - Select results from one table and for each row select all rows that have the same id from another table 选择同一表中的行数 - Select count of rows from the same table 如何更新表,但需要从同一表的另一个选择和另一个表中获取更新值? - how can I update a table but needing to get the update value from another select of the same table and other one? 如何在同一选择查询中将一个表中的值交换到另一表中的值? - How can I swap a value from one table to that of another table in the same select query? 选择一个表的一部分并计算另一个表的行 - Select parts of one table and count rows of another 如何在SQL中显示计数值,而不是列出同一表中的许多行? - How can I show a count value in SQL instead of listing out many rows in the same table? SELECT COUNT 基于同一张表中的另一行 - SELECT COUNT Based on another row in the same table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM