【问题标题】:return null if no rows found oracle query with IN clause如果没有找到行,则返回 null oracle 使用 IN 子句查询
【发布时间】:2016-10-24 01:16:36
【问题描述】:

我有一个三列的表。 我用 IN 子句查询该表。

select column1 from table1 where column1 in (1,2,3) order by column2, column3

table1 在 column1 中仅包含值 1 和 2。我想在我的结果中也返回不可用的值,并且应该在底部进行排序。

示例数据

第 1 列第 2 列第 3 列

1   100 11

2   101 50

输出,不可用的值应该在最后。

第 1 列第 2 列第 3 列

1   100 11

2   101 50

3 null null

我尝试使用 NVL 进行子查询,例如 select nvl((select.. in(1,2,3)),null) from dual,由于 IN 子句,我得到单行子查询返回多行问题,这是预期的。

也尝试了工会,但没有任何效果。如果有帮助,那就太好了。谢谢

【问题讨论】:

  • 使用解码功能或向我们展示您的查询,我们会为您提供帮助。
  • @Prathyush 我也尝试了解码,但表中不存在的值被忽略。 select col1,decode(col1, NULL,'zero', col1) from table1 where col4 = 2 and col1 in (1,2,3)
  • 这里的 col1 是什么?是主键吗?
  • 表1有col1,col2,col3,col4和col1,col2,col3组合是表中的主键
  • 那你必须尝试使用​​子查询。有类似 select decode((subquery from table1),null,'test',(subquery from table1)) from table 1. 我知道这会让你的查询很慢

标签: oracle plsql


【解决方案1】:

如果您不能从另一个表中获取 1,2,3 值,您可以尝试:

with t1 as (
  select col1,col2,col3
  from tab1
  where cod_flusso in ('1','2','3')),
t2 as (
  select '1' as col1,null,null
  from dual
  union
  select '2',null,null
  from dual
  union
  select '3',null,null
  from dual)
select t2.col1,col2,col3
from t2
left outer join t1
on t1.col1= t2.col1

如果你可以在第二个表中存储 1,2,3 个值,然后使用左外连接,那就更好了。

【讨论】:

  • 对于联合体,您对值进行了硬编码,但我将动态传递 IN 子句的值。第二张桌子是不可能的。所有值都在单个表中
  • 你是对的!出于这个原因,我建议使用第二个表......你能解释一下用于动态提取 IN 子句中的值的逻辑吗?
【解决方案2】:

我认为你可以使用 union all 来做到这一点:

select column1 from table1 where column1 in (1,2,3) order by column2, column3 
union all 
select null from table1 where column1 not in (1,2,3) order by column2, column3 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2018-10-23
    相关资源
    最近更新 更多