查询语句: select Tname,Salary from Teacher where Dno = “D01” AND salary IN( select salary from teacher where Dno =(select DNO from department where Dname=“国贸”) );
例:求工资介于“张三”与“里司”两个之间的职工
select *
from teacher
where
Salary >= (select MIN(Salary) from teacher where Tname IN ("张三", "里司")) AND
Salary <= (select MAX(Salary) from teacher where Tname IN ("张三", "里司");
4.3.4 在from语句中使用子查询,对查询结果定义表名及列名
例:求平均成绩超过80分的学号及平均成绩
select Sno, avg_G
from (select Sno, avg(Grade) from SC group by Sno) AS RA(Sno, avg_G)
where avg_G > 80;
select Sname
from student
where not exists (
select *
from Course
where not exists (
select * from SC where
student.sno=SC.sno AND Course.Cno=SC.Cno
)
);
例:查询至少选修了S1所选的全部课程的学生名
select Sname
from student
where not exists(
select *
from SC SCX
where
SCX.sno="s1" AND
not exists (
select *
from SC SCY
where student.sno=SCY.sno AND SCX.Cno=SCY.Cno
)
);
6、SQL的集合操作
属性个数必须一致、对应的类型必须一致
属性名可以不一致, 最终结果集采用第一个结果的属性名
缺省为自动去除重复元组,除非显式说明ALL
order by放在整个语句的最后
6.1 “并”操作,例:查询计算机系的学生或者年龄不大于19岁的学生,并按年龄倒排序。
select * from student where Sdept="CS"
UNION
select * from student where AGE <= 19
order by AGE desc
6.2 “交”操作,例:查询计算机系的学生并且年龄不大于19岁的学生,并按年龄倒排序。
(select * from student where Sdept = "CS")
INTERSECT
(select * from student where AGE <= 19)
order by AGE desc
6.3 “差”操作,例:查询选修课程1但没有选修课程2的学生。
select Sname, Sdept
from student
where sno IN (
(select sno from SC where Cno="1")
EXCEPT
(select sno from SC where Cno="2")
)
7、插入操作
格式:insert into 表名[(列名1,…)] values (列值1,…)
插入一已知元组的全部列值
insert into student values("2003001", "陈冬", 18, "男", "电商", "管理学院", "徐州");
插入一已知元组的部分列值
insert into SC(Sno,Cno) values ("2003001", "C003");
插入子查询的结果
例:设关系S_G(Sno,avg_G),把平均成绩大于80的男生的学号及平均成绩存入S_G中
insert into S_G(sno,avg_G) (
select sno, avg(GRADE)
from SC
where Sno IN (select Sno from Student where SEX="男")
group by Sno
having avg(GRADE) > 80
);