Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL问题,挑战_Sql - Fatal编程技术网

SQL问题,挑战

SQL问题,挑战,sql,Sql,假设我们有两个实体:教师和学生 每个老师有多个学生 现在我想: 查询最多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 但这还不是全

假设我们有两个实体:教师和学生

每个老师有多个学生

现在我想:

查询最多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中实现这一点?

为每个选定的教师使用子查询。

伪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

请准确点。生成的关系应该有什么标题?这是什么数据库?这是什么数据库?在我看来,您的GROUP_CONCAT语法与SQLite不同,最新的MySQL GA 5.1版在您的查询中出现语法错误。我需要在通用数据库上执行此操作。我认为第二个子查询在再次查看后不正确。它只会返回10名学生,而不是每个教师返回10名学生。