[英]How to use Look up In Oracle query
I have a reference table called customer that has cust_id, cust_name ..., there are also other tables that have cust_name, cust_location....so on.我有一个名为 customer 的参考表,它具有 cust_id、cust_name ...,还有其他表具有 cust_name、cust_location ....等等。 I need to look up cust_location using cust_name from all these tables.
我需要使用 cust_name 从所有这些表中查找 cust_location。 how do I write the query in oracle SQL?
如何在 oracle SQL 中编写查询?
select cust_id, cust_name from customer
from (
select cust_name as cust_location from tb1
union all
select cust_name as cust_location from tbl2
union all
select cust_name as cust_location from tbl3
)
expected result.......looks like
预期结果.......看起来像
You were nearly there..你快到了..
select cust_location, table_name
from (
select cust_name as cust_location, 'tb1' as table_name from tb1
union all
select cust_name as cust_location, 'tb2' as table_name from tbl2
union all
select cust_name as cust_location, 'tb3' as table_name from tbl3
)
You can get Oracle's help to write this, actually:你可以得到 Oracle 的帮助来写这个,实际上:
SELECT 'select cust_name as cust_location, '''|| table_name ||''' as table_name from ' || table_name || char(13) || chr(10) || 'union all'
FROM all_tab_columns
WHERE column_name = 'CUST_NAME'
This SQL will generate an output that is the SQL in brackets in the first one;该 SQL 将生成一个输出,即第一个括号中的 SQL; copy it out of the results grid and paste it into the query window
将其从结果网格中复制并粘贴到查询窗口中
You want all locations regardless of the customer.无论客户如何,您都需要所有位置。 Some locations are null and must be ignored.
某些位置为空且必须被忽略。 I suppose that locations can occur more than once in a table, so I am using
DISTINCT
:我想位置可以在一个表中出现多次,所以我使用
DISTINCT
:
select distinct cust_name as cust_location, 'tb1' as table_name from tb1 where cust_name is not null
union all
select distinct cust_name as cust_location, 'tb2' as table_name from tbl2 where cust_name is not null
union all
select distinct cust_name as cust_location, 'tb3' as table_name from tbl3 where cust_name is not null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.