为了简化SQL语句,可以将语句分成若干个视图来操作,但是创建的试图将会作为对象保存在数据库中,但经常有一些语句只是临时使用,所以在sql-99规范中有了with as 语句,该语句实质上就是创建临时视图,来帮助你简化语句并使语句结构更清晰更容易阅读。
下面的测试中会用到3张表,courseresults(课程-学生-成绩表)、courses(课程表)、students(学生表),先给出建表语句:
create table COURSERESULTS
(
CID NUMBER,
SID NUMBER,
SCORE FLOAT not null
)
create table COURSES
(
CID NUMBER not null,
CNAME VARCHAR2(100) not null,
TID NUMBER,
CREDITS NUMBER not null
)
create table STUDENTS
(
SID NUMBER not null,
SNAME VARCHAR2(50) not null,
SEX CHAR(1),
BIRTHDATE DATE,
EMAIL VARCHAR2(50)
)
例1:获取student表全部数据
with s as
(select * from students)
select * from s;
例2:获取小于平均成绩的学生学号和成绩
with c as
(select avg(score) as value from courseresults)
select sid,score from courseresults,c where score>c.value;
例3:获取课程平均成绩大于85分的男生的学号
with
s1 as
(select sid from courseresults group by sid having avg(score)>85),
s2 as
(select sid from students where sex='m')
select * from s1 intersect select * from s2;
结论:使用with as语句的确可以使复杂的SQL语句具有更清晰的结构。