一
values ('1',2,3) 为一行 ‘1’ 2 3 行数据类型可以不同 values ('1',2,3),('f',5,6) 为两行
(values 1,2,3) 为一列
1
2
3
所以数据类型必须一样,不然报错
二 with做临时表,with还可以递归查询
二.1 with可以和select语句组合做临时表
CREATE TABLE USER ( NAME VARCHAR(20) NOT NULL,--姓名 DEGREE INTEGER NOT NULL,--学历(1、专科 2、本科 3、硕士 4、博士) STARTWORKDATE date NOT NULL,--入职时间 SALARY1 FLOAT NOT NULL,--基本工资 SALARY2 FLOAT NOT NULL--奖金 );
假设现在让你查询一下那些 1、学历是硕士或博士 2、学历相同,入职年份也相同,但是工资(基本工资+奖金)却比相同条件员工的平均工资低的员工。(哈哈,可能是要涨工资),不知道你听明白问题没有?该怎么查询呢?
对比两种方式:
a
WITH TEMP1(NAME,DEGREE,WORDDATE,SALARY) AS ( SELECT NAME,DEGREE,YEAR(STARTWORKDATE) AS WORDDATE, SALARY1+SALARY2 AS SALARY FROM USER WHERE DEGREE IN (3,4) ), TEMP2 (DEGREE,WORDDATE,AVG_SALARY) AS ( SELECT DEGREE,YEAR(STARTWORKDATE) AS WORDDATE, AVG(SALARY1+SALARY2) AS AVG_SALARY FROM USER WHERE DEGREE IN (3,4) GROUP BY DEGREE,YEAR(STARTWORKDATE) ) SELECT NAME FROM TEMP1, TEMP2 WHERE TEMP1.DEGREE=TEMP2.DEGREE AND TEMP1.WORDDATE=TEMP2.WORDDATE AND SALARY<AVG_SALARY;
b
WITH TEMP1(NAME,DEGREE,WORDDATE,SALARY) AS ( SELECT NAME,DEGREE,YEAR(STARTWORKDATE) AS WORDDATE, SALARY1+SALARY2 AS SALARY FROM USER WHERE DEGREE IN (3,4) ), TEMP2 (DEGREE,WORDDATE,AVG_SALARY) AS ( SELECT DEGREE,WORDDATE, AVG(SALARY) AS AVG_SALARY FROM TEMP1 GROUP BY DEGREE,WORDDATE ) SELECT NAME FROM TEMP1, TEMP2 WHERE TEMP1.DEGREE=TEMP2.DEGREE AND TEMP1.WORDDATE=TEMP2.WORDDATE AND SALARY<AVG_SALARY;
递归用法:
论坛首页 --数据库开发 ----DB2 ------DB2 文章1 --------DB2 文章1 的评论1 --------DB2 文章1 的评论2 ------DB2 文章2 ----Oracle --Java技术
CREATE TABLE BBS ( PARENTID INTEGER NOT NULL, ID INTEGER NOT NULL, NAME VARCHAR(200) NOT NULL---板块、文章、评论等。 ); insert into bbs (PARENTID,ID,NAME) values (0,0,'论坛首页'), (0,1,'数据库开发'), (1,11,'DB2'), (11,111,'DB2 文章1'), (111,1111,'DB2 文章1 的评论1'), (111,1112,'DB2 文章1 的评论2'), (11,112,'DB2 文章2'), (1,12,'Oracle'), (0,2,'Java技术');
查询一下DB2的所有文章及评论,怎么办?
WITH TEMP(PARENTID,ID,NAME) AS ( SELECT PARENTID,ID,NAME FROM BBS WHERE NAME='DB2'---语句1 UNION ALL---语句2 SELECT B.PARENTID,B.ID,B.NAME FROM BBS AS B, TEMP AS T WHERE B.PARENTID=T.ID---语句3 ) SELECT NAME FROM TEMP;---语句4