第3章_关系数据库标准语言(SQL)_006_由元组关系演算到SQL Command_002_案例_05_关于:至少、至多、恰好

1. 查询至少选修了3门的学生的学号 ===》
SELECT SN, S.SNo
FROM S, SC
WHERE S.SNo = SC.SNo
GROUP BY SN, S.SNo HAVING (
    COUNT(CNo) >= 3
  )
或者
SELECT SN, SNo
FROM S
INNER JOIN SC ON S.SNo = SC.SNo
GROUP BY SN, S.SNo HAVING (
    COUNT(CNo) >= 3
  )
  
  
2. 查询至多选修了2门的学生的学号 ===》
SELECT SN, SNo
FROM S
EXCEPT
SELECT SN, S.SNo
FROM S, SC
WHERE S.SNo = SC.SNo
GROUP BY SN, S.SNo HAVING (
    COUNT(CNo) > 2
  )
或者
SELECT SN, SNo
FROM S
EXCEPT
SELECT SN, S.SNo
FROM S
INNER JOIN SC ON S.SNo = SC.SNo
GROUP BY SN, S.SNo HAVING (
    COUNT(CNo) > 2
  )
但是千万不能写成如下这样的形式!!!
SELECT SN, S.SNo
FROM S
INNER JOIN SC ON S.SNo = SC.SNo
GROUP BY SN, S.SNo HAVING (
    COUNT(CNo) <= 2
  )
因为SC中CNo与SNo为主键,所以CNo上不能为NULL,所以SC表中不能记录没有选修课程的同学的记录,所以这样就会漏掉没有选修课程:COUNT(CNo) = 0的情况,这时就必须使用EXCEPT将总的集合与' > num'的集合做差集。
  
  
3. 查询恰好选修了3门课程的同学 ===》
SELECT SN, S.SNo
FROM S
INNER JOIN SC ON S.SNo = SC.SNo
GROUP BY SN, S.SNo HAVING (
    COUNT(CNo) = 3
  )

posted @ 2020-04-06 09:06  BNTU  阅读(211)  评论(0编辑  收藏  举报