[英]How to use Look up In Oracle query
我有一个名为 customer 的参考表,它具有 cust_id、cust_name ...,还有其他表具有 cust_name、cust_location ....等等。 我需要使用 cust_name 从所有这些表中查找 cust_location。 如何在 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
)
预期结果.......看起来像
你快到了..
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
)
你可以得到 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'
该 SQL 将生成一个输出,即第一个括号中的 SQL; 将其从结果网格中复制并粘贴到查询窗口中
无论客户如何,您都需要所有位置。 某些位置为空且必须被忽略。 我想位置可以在一个表中出现多次,所以我使用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.