WITH子句在ORACLE 11G中使用UNION ALL

时间:2017-10-10 06:01:09

标签: oracle plsql oracle11g with-statement

请您给我以下代码的替代查询。

PLSQL代码

我用过WITH Clause变量TEMP在UNION ALL查询中使用两个地方,帮助减少一次在UNION ALL查询中使用TEMP变量,

DECLARE

  CURSOR CUR Is  
    WITH TEMP AS    
     (SELECT 1 ONE FROM DUAL UNION ALL SELECT 2 ONE FROM DUAL)   
    SELECT RNO, NAME  FROM STUDENT, TEMP T  WHERE RNO = T.ONE   
    UNION ALL   
    SELECT RNO, NAME FROM STUDENT1, TEMP T WHERE RNO = T.ONE;   
BEGIN

  FOR I IN CUR LOOP  
    DBMS_OUTPUT.PUT_LINE(I.RNO||':'||i.name);   
  END LOOP;

END;

表格创建脚本

create table student1(rno number,name varchar2(30))    

insert into student1 values(1,'chidam1')    
insert into student1 values(2,'ram1')    
insert into student1 values(3,'divi1')

create table student(rno number,name varchar2(30))

insert into student values(1,'chidam')
insert into student values(2,'ram')
insert into student values(3,'divi')

1 个答案:

答案 0 :(得分:0)

就像乘法在代数中对加法的分配一样,笛卡尔积在集合论中对于并集是分布的,所以INNER JOIN在SQL中对UNION ALL进行分配。

您可以像这样重写SELECT语句:

with
     temp          as ( ... - your definition here     )
   , student_union as ( select rno, name from student 
                        UNION ALL
                        select rno, name from student1 )
select s.rno, s.name from student_union s inner join temp t on s.rno = t.one
........................

一些注意事项......尽可能使用ANSI连接语法(SQL标准),不要使用旧的,不推荐使用的Oracle语法。此外,对连接中的所有列使用限定符(表别名),即使它们并非总是严格必要;代码更容易阅读。