使用oracle 11g联合所有查询

时间:2016-02-24 01:43:34

标签: sql oracle11g

select x,y
from table 1, table 2
where table1.location = 'IL' and table1.col1 = table2.col1 
union all 
select x,y
from table 1, table 3
where table1.location = 'NY' and table1.col2 = table3.col2 
union all 
select x,y
from table 1, table 4
where table1.location = 'KY' and table1.col1 = table4.col1 
union all 
select x,y
from table 1, table 5
where table1.location = 'TX' and table1.col1 = table5.col1 

我们每15分钟运行一次,如果在表1中创建了任何新行,则执行union all查询。

目前我正在这样做,

select * from
(select id,x,y from table 1, table 2 where table1.location = 'IL' and table1.col1 = table2.col1 

union all 

select id,x,y from table 1, table 3 where table1.location = 'NY' and table1.col2 = table3.col2 

union all 

select id,x,y from table 1, table 4 where table1.location = 'KY' and table1.col1 = table4.col1 

union all 

select id,x,y from table 1, table 5 where table1.location = 'TX' and table1.col1 = table5.col1) usr1, 
(select id,x,y,location from table 1 where create_date >= SYSDATE - 15 / 1440) usr2, 
where usr2.location in ('IL','NY','KY','TX') and usr1.id = usr2.id 

假设在表1中的15分钟间隔内创建了10行,其中

2 rows in 'IL' 
2 rows in 'NY' 
2 rows in 'KY' 
and 4 rows in 'TX' 

有没有办法使用oracle 11g我只能传递' IL'第一个查询,2行' NY'到第2行和第4行' TX'对union all查询中的每个条件进行第4次查询。

1 个答案:

答案 0 :(得分:0)

也许看看使用'WITH CLAUSE'在将行传递给表之前配对它们。例如:

WITH less_rows as (
  select id,x,y,location
    from table1
   where create_date >= SYSDATE - 15 / 1440
     and location in ('IL','NY','KY','TX')
)
select x,y
from less_rows, table2
where less_rows.location = 'IL' and less_rows.location = table2.location 
union all 
select x,y
from less_rows, table3
where less_rows.location = 'NY' and less_rows.location = table3.location 
union all 
select x,y
from less_rows, table4
where less_rows.location = 'KY' and less_rows.location = table4.location 
union all 
select x,y
from less_rows, table5
where less_rows.location = 'TX' and less_rows.location = table5.location

我假设优化器非常智能,只能执行一次WITH查询,并在所有联合查询中重复使用结果。

相关问题