数据库-基础篇 第七讲(含习题)未完结
IN 子查询
- (NOT)IN子查询:表达式 【NOT】in (子查询)
例:列出张三、王三同学所有信息:
Select *
From Student
Where Sname in
(‘张三’,’王三‘);
列出选秀了001号课程学生的学号和姓名:
Select S#, Sname
From Student
Where S# in
(Select S# From SC Where C#=‘001’);
列出选秀了001号课程和002号课程的学生的学号:
Select S#
From SC
Where C#=‘001’ and
S# in (Select S# from SC where C#=‘002’);
列出没学过李明老师课程的所有同学姓名:
Select Sname
From Student
Where S# NOT in
(Select S#
From SC, Course C, Teacher T
Where T.tname=‘李明’ and SC.C#=C.C# and T.T#=C.T#);
-
以上例子均为非相关子查询
-
相关子查询:
TheaSome/ALL子查询
- 表达式 theata some (子查询)
表达式 theata all(子查询)
例:找出工资最低的教师姓名
Select Tname
From Teacher
Where Salary <= all (Select Salary From Teacher);
找出001号课成绩不是最高的所有学生学号:
Select S#
From SC
Where C#=‘001’ and Score < some (Select Score From SC Where c#=‘001’);
所有课程都不及格学生姓名**(相关子查询):**
Select Sname
From Student
Where 60>all (Select Score From SC Where S#=Student.S#);
- = some(子查询)等价于 in (子查询)
not in (子查询)等价于 <> all (子查询)
(Not)Exists子查询——集合基数的测试
- 测试集合是否为空,是否存在重复元组
用SQL语言表达并-差-交操作
- 例:求学过002号课或学过003号课的同学学号
*Select S# From SC Where C#=‘002’
UNION
Select S# From SC Where C#=‘003’;
Select S#
From SC
Where C#=‘002’ or C#=‘003’;
-
交运算没有增强SQL表达能力:
Select S# From SC Where C#=‘002’
INTERSECT
Select S# From SC Where C#=‘003’;
Select S# From SC Where C#=‘002’ and S# in
(Select S# From SC Where C#=‘003’ );
4.差运算,没有增强SQL的表达能力
求没选002号课程的学生学号:
Select DISTINCT S# From SC
EXCEPT
Select S# From SC Where C#=‘002’;
Select DISTINCT S# From SC SC1
Where not exists (Select * From SC Where C#=‘002’ and S#=SC1.S#);
用SQL语句处理空值
-
找出空值:
Select Sname From Student
Where Sage is null;
注意:空值不能进行运算 -
null处理小结:
(1)除了is [not ] null之外,空值不满足任何条件;
(2)如果null参与算术运算,则算术运算表达式为null;
(3)如果null参与比较运算,则结果视为false;
(4)如null参与聚集运算,则除count(*)之外都忽略null;