简体   繁体   中英

Oracle SQL: single SELECT request for multiple owners

I would like your advice on the best method to use.

From a single Oracle server, we have 3 different owners that contain the exact same tables/data structures. Essentially, the owners allow us to separate the data by administrative regions.

Currently, when I want to do a SQL query on the entire data set (regions), I have to do 3 separate queries:

select * from owner1.Table1 union all
select * from owner2.Table1 union all
select * from owner3.Table1

In this simple example, there are no issues, but if the query is complex, it quickly becomes very difficult to maintain.

So, would there be a more efficient way to make only one global query instead of 3. I guess it's possible to do it via a PL/SQL script, or Dynamic SQL, but I don't know...

Basically, I would like to be able to do (where owners would contain the names of my 3 owners):

select * from owners.Table1

It is not possible to build views that would contain the data of all 3 owners (there would be too many).

Thanks

In this simple example, there are no issues, but if the query is complex, it quickly becomes very difficult to maintain.

So, would there be a more efficient way to make only one global query instead of 3.

Use a sub-query factoring clause (aka a CTE) to combine the queries with the simple UNION ALL queries and then perform the complex query on the combined table (rather than trying to perform the queries on the individual tables):

WITH subquery_name AS (
  select * from owner1.Table1 union all
  select * from owner2.Table1 union all
  select * from owner3.Table1
)
SELECT <your complex query>
FROM   subquery_name;

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