【问题标题】:Oracle Sql - I have two tables and need to filter table1 with results from table2. I need to return all of table1 if table2 is emptyOracle Sql - 我有两个表,需要使用 table2 的结果过滤 table1。如果 table2 为空,我需要返回所有 table1
【发布时间】:2023-04-01 05:20:02
【问题描述】:

我目前正在将逗号分隔的字符串转换为字段名称为 ID 的数字表。然后,如果生成的表为空,我将尝试执行 nvl 以全选。

table1.ID = NVL(table2.ID, table1.ID)

我有两个表,需要使用表 2 中的结果过滤表 1。如果 table2 为空,我需要返回所有 table1。

场景一

表1

ID    
1    
2    
3    
4

表 2(空)

ID

Return rows 1, 2, 3, 4

场景二

表1

ID    
1    
2    
3    
4

表2

ID    
2
3

返回第 2、3 行

【问题讨论】:

    标签: sql oracle12c


    【解决方案1】:

    您可以在where 子句中使用过滤:

    select t1.id
    from table1 t1
    where not exists (select 1 from table2) or
          exists (select 1 from table2 t2 where t2.id = t1.id);
    

    我不认为join 是表达这种逻辑的正确方式。

    【讨论】:

    • 如果我可以在 table2 中填充一个空行并使用 NVL 连接会比这更有效吗?我在表 1 中有大约 100 万条记录。
    • @Matt 。 . .这可能是最有效的解决方案。我猜你已经在ids 上有了索引,这是需要的。
    【解决方案2】:

    你也可以使用UNION

    select t1.id
    from table1 t1 
    where not exists (select 1 from table2 where id = t1.id) union all
    select t2.id
    from table2 t2
    where exist (select 1 from table1 where id = t2.id);
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      相关资源
      最近更新 更多