繁体   English   中英

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

[英]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 empty

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

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

我有两个表,需要用table2的结果过滤table1。 如果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行

您可以在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不是表达这种逻辑的正确方法。

您也可以使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM