简体   繁体   中英

union all query using oracle 11g

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 

we run every 15 minutes and if there are any new rows created in table 1 then execute the union all query.

Currently I am doing this,

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 

Suppose there are 10 rows created during a 15 minutes interval in table 1, out of which

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

Is there any way using oracle 11g I can pass only those 2 rows in 'IL' 1st query, 2 rows in 'NY'to 2nd and 4 rows in 'TX' to 4th query to each condition in the union all query.

Perhaps take a look at using a 'WITH CLAUSE' to pair down your rows prior to passing them to the tables. For example:

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

I'm assuming the optimizer is smart enough to only perform the WITH query once, and re-use the results across all of the union'd queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM