假设我们有两个实体:老师和学生。
每位老师都有多名学生。
现在我想:
最多可查询5名教师,每位教师最多不超过10名学生。
到目前为止,这可以通过以下方式轻松完成:
select *,
(
select GROUP_CONCAT('<sid>',students.name,'</sid>') from students on
teachers.id=students.teacher limit 10
) as students
from teachers limit 5
但这还不是整个故事。
和
如果任何一位教师的学生人数超过10人,则该教师应返回true
,否则false
如何在SQL中执行此操作?
答案 0 :(得分:0)
答案 1 :(得分:0)
为每位所选教师使用子查询。
答案 2 :(得分:0)
伪SQL:为5位教师中的每位教师分别为10名学生提供一行结果
select t.teacher_id, s.student_id,
case when t2.count > 10 then 'true' else 'false' end
from
(select top 5 *
from teachers
order by teacher_id) t
join
(select top 10 *
from students s1 join teachers t1 on s1.teacher_id = t1.teacher_id
order by student_id) s
on t.teacher_id = s.teacher_id
join
(select teacher_id, count(*) as count
from teachers t join students s on t.teacher_id = s.teacher_id
group by teacher_id) t2
on t2.teacher_id = t.teacher_id