簡體   English   中英

我可以選擇另一個表中與該表中的 FK 具有相同值的行數嗎?

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

對不起,如果那是可怕的措辭。 基本上我需要做一個查詢,告訴我“俱樂部”的俱樂部名稱和描述,以及該俱樂部的學生總數。 學生只能在 1 個俱樂部中,因此 clubID 是“學生”中的外鍵。

我嘗試使用下面的內容,但很快就發現我離答案還差得很遠。 這可能嗎?

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

您需要使用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

如果要包含沒有學生的俱樂部,則需要外部聯接或相關子查詢:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM