我在一次面试中遇到了这个问题,我不太明白。我有三张table:一张学生桌,一张班级桌和一张连接其他两张table的table。这是他们的基本模式。
STUDENT
student_id | student_name
-----------+-------------
int | varchar(30)
CLASS
class_id | class_name
---------+-----------
int | varchar(30)
ROSTERS
student_id | class_id
-----------+---------
int | int
名册表显示哪些学生正在上哪些课。我该如何写一个查询来显示哪些学生正在上两门或更多的课?
5条答案
按热度按时间vjrehmav1#
这是最简单的方法。
yyhrrdl82#
此查询将执行您想要的操作:
它计算了所有不同的
class_id
中的值roster
每个学生(num_classes
)只返回2个或更多的学生(HAVING num_classes >= 2
).注意我用了
LEFT JOIN
为了抓住所有的学生,但是,因为你只想要那些超过一个班,这是没有必要的,你可以使用一个直JOIN
.另外请注意,没有必要
JOIN
这个class
这个问题的表格,但是如果你想要学生参加的课程的名称,你需要。8e2ybdfx3#
你可以用
join
,count
,having
以及group by
要获得所需的输出:pxyaymoc4#
你需要加入两个表,学生和名册(我已经使用了内部连接,如果需要,这可以根据需要更改),计算每个学生正在上课的数量。
6mw9ycah5#
这将起作用: