【问题标题】:Use subquery from select clause in where clause在 where 子句中使用 select 子句中的子查询
【发布时间】:2021-11-16 23:57:15
【问题描述】:

我正在用 Oracle SQL 编写查询,我想在 where 子句的 select 子句中使用子查询的结果。自定义列使用 case 表达式设置值。 简单例子:

select 
 column_x,
 column_y,
 (case when (select something from table_x) > 1
  then 'Yes' else 'No') "yesno",
 column_z
from
 example_table
where
 yesno = 'Yes'

如果可能的话,实现这一目标的方法是什么? 谢谢。

【问题讨论】:

  • 在这种情况下,您可以在选择列表中硬编码'yes',并将条件移至where 子句。

标签: sql oracle select where-clause


【解决方案1】:

假设子查询返回不超过 1 行,您的查询基本上没问题。但是您不能在子查询中使用该列。但是,您可以将逻辑移至 from 子句:

select t.column_x, t.column_y, x.yesno, t.column_z
from example_table t left join
     (select case when something > 1 then 'Yes' else 'No' end as yesno
      from table_x
     ) x
     on 1=1
where x.yesno = 'Yes';

如果查询确实是相关子查询,那么可以使用left join lateral

【讨论】:

    【解决方案2】:

    你可以这样做:

    select 
     column_x,
     column_y,
     yesno,
     column_z
    from (
      select 
       column_x,
       column_y,
       (case when (select something from table_x) > 1
        then 'Yes' else 'No') yesno,
       column_z
      from
       example_table
    )
    where
     yesno = 'Yes'
    

    注意:我从 "yesno" 中删除了您的双引号,因为它们强制列名区分大小写,这是不可取的。

    当然,在这个例子中你也可以这样做:

    select 
     column_x,
     column_y,
     'Yes' yesno,
     column_z
    from
     example_table
    where
     (select something from table_x) > 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2014-02-23
      相关资源
      最近更新 更多