【问题标题】:SQL query without COUNT() to get all the students taking all the classes available [closed]没有 COUNT() 的 SQL 查询让所有学生参加所有可用的课程 [关闭]
【发布时间】:2022-01-17 04:42:02
【问题描述】:

有没有一种方法可以在不使用 COUNT() 或任何其他聚合函数的情况下只让参加 CLASS 中所有可用课程的学生获得? 出于好奇,这只是一个问题,只是想知道是否有 COUNT() 的替代方法。 DBMS 是 PostgreSQL。 表格如下所示:

STUDENT
student_id | student_name
-----------¦-------------
int        | varchar(30)

CLASS
class_id | class_name
---------¦-----------
int      | varchar(30)

REGISTRATION
student_id | class_id
-----------¦---------
int        | int

【问题讨论】:

  • 什么是 DBMS?
  • 家庭作业?你是怎么解决这个问题的?
  • 尝试:SELECT S.*,C.*,R.* FROM STUDENT S, CLASS C, REGISTRATION R; 这将得到您问题描述中的答案.....
  • @Jayvee PostgreSQL
  • @Luuk 只是出于好奇想知道。你的答案并不是我真正想要的……我指定了我的问题。

标签: sql postgresql count


【解决方案1】:

双重NOT EXISTS也可以得到所有课程注册的学生。

它返回不属于尚未注册所有课程的学生。

select *
from student as st1
where not exists (
    select 1
    from student as st2
    cross join class as cl
    where st2.student_id = st1.student_id
      and not exists (
        select 1
        from registration as re
        where re.student_id = st2.student_id
          and re.class_id = cl.class_id
      )
)

EXCEPT 获取所有学生,但未注册所有课程的学生除外。

select *
from student
except
select distinct st.*
from student as st
cross join class as cl
left join registration as re 
    using(student_id, class_id) 
where re.class_id is null

【讨论】:

    【解决方案2】:

    这将显示在所有课程中注册的学生:

    select * from student
    where student_id not in
    (
        select student_id from 
        (
            select 
            s.student_id, c.class_id
            from student s cross join class c
            except
            select student_id, class_id
            from registration
        ) classmissed
    ) 
    

    解释:

    首先,学生和班级之间的交叉连接将返回学生/班级的所有可能组合 然后删除实际注册,这将留下未在所有课程中注册的学生 最后,NOT IN 该集合将为我们提供在所有课程中注册的学生。

    db-fiddle

    https://www.db-fiddle.com/f/gjuScoNeABT91aj1eTWC82/0

    【讨论】:

      猜你喜欢
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      相关资源
      最近更新 更多