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

时间:2011-03-07 21:31:25

标签: sql oracle oracle10g

我有这样的查询: 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 个答案:

答案 0 :(得分:3)

除了正确说的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'的行,那么您需要将该条件放在中:

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

如果你确定table1和table2之间没有重复,我推荐UNION ALL超过UNION,因为它比它快。

答案 1 :(得分:1)

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(仅用于基本语法和健全性检查)。

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