首页 文章

在where子句中使用别名的解决方法:oracle10g

提问于
浏览
0

我有这样的查询: select data.* from ((select table1.col1 as "a") union (select table2.col2 as "b")) data where 1 = 1

如果我希望过滤“a”列,我该如何添加caluse到这个?我知道我不能使用别名,但是如何编写where子句呢?我试过了:

select data.* 
from (
   select table1.col1 as "a"
   union 
   select table2.col2 as "b"
) 
data where 1 = 1 
 and data.a = 'someValue'

也:

select data.* 
from (
   select table1.col1 as "a"
   union 
   select table2.col2 as "b"
) data 
where 1 = 1 
  and data.table1.col1 = 'someValue'

两者都有错误

2 回答

  • 3

    Oracle中的所有选择都需要FROM子句:

    select data.* 
      from ((select 1 as a FROM dual) union 
            (select 2 as b FROM dual)) DATA 
     where 1 = 1 
       and data.a = '1'
    

    在我的示例中将您的表名替换为dual(仅用于基本语法和健全性检查) .

    此外,除非您需要将别名设置为小写,否则更容易省略别名中的双引号,以避免在引用别名的任何位置使用双引号 .

  • 1

    除了DBCookie正确说的(我假设内部查询中缺少的只是一个复制和粘贴错误):

    具有别名 data 的派生表仅具有单个列,该列由联合中第一个SELECT的列名确定 . 此列名为 "a" (不是 a ),因为引号现在区分大小写 .

    如果您不坚持使用小写列名称,则只需忽略内部查询中的引号 .

    select data.* 
    from (
       select col1 as a
       from table1
       union 
       select col2   --- you can leave out the alias here it's useless.
       from table2  
    ) 
    WHERE data.a = 'someValue' -- I remove the 1=1 as it doesn't serve any purpose
    

    如果您坚持在引号中使用别名,则必须在WHERE子句中使用它们:

    WHERE data."a" = 'someValue'
    

    但是这也将过滤掉来自table2的值并在其col2中具有'someValue' . 我不确定这是不是你想要的 . 如果你想要过滤掉来自table1的行并且在col1中有'someValue',那么你需要将这个条件放在union中:

    select data.* 
    from (
       select col1 as a
       from table1
       where col1 = 'someValue' 
       union 
       select col2
       from table2  
    ) data
    

    如果您确定table1和table2之间没有重复项,我建议使用 UNION ALL 而不是 UNION ,因为它比它更快 .

相关问题