【问题标题】:How to use Look up In Oracle query如何使用 Lookup In Oracle 查询
【发布时间】:2020-10-05 17:47:22
【问题描述】:

我有一个名为 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
    )

预期结果.......看起来像

【问题讨论】:

  • 似乎您需要熟悉JOIN 和与表格相关的“键”(您的问题中没有提供)。
  • 除了问题,你为什么要像cust_name as cust_location 那样做?样本数据和预期结果真的很有帮助。
  • 请提供样本数据和期望的结果。不清楚您所说的“查找”是什么意思。
  • 对于特定的 cust_name,cust_location 应该只出现在这些表之一(tb1,tb2,tb3...)如果它出现在 tb1 中,则 cust_location 的值对于其他表应该为 null .所以我需要通过它所在的表查找并列出 cust_location
  • 您希望结果看起来如何?您能否也添加您的预期结果。

标签: sql oracle


【解决方案1】:

你快到了..

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;将其从结果网格中复制出来并粘贴到查询窗口中

【讨论】:

    【解决方案2】:

    无论客户如何,您都想要所有位置。某些位置为空,必须忽略。我想位置可以在一个表中出现不止一次,所以我使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多