[英]invalid identifier error in oracle due to column alias
我有一个查询如下
select t.col1,
t.col2,
(select count(col1)
from tab
where col1 = t.col1
and col2 = t.col2
) as col3
from tab t
where col3 > 1
该查询给出了“col3无效标识符”错误。
我尝试了不同的变体来定义我在下面给出的别名以及我在使用它时得到的错误
select t.col1, t.col2, (select count(col1) from tab where col1 = t.col1 and col2 = t.col2 ) as "col3" from tab t where col3 > 1
错误:col3无效标识符
select t.col1, t.col2, (select count(col1) from tab where col1 = t.col1 and col2 = t.col2 ) as 'col3' from tab t where [col3] > 1
错误:在哪里丢失表达式
select t.col1, t.col2, (select count(col1) from tab where col1 = t.col1 and col2 = t.col2 ) "col3" from tab t where [col3] > 1
错误:在哪里丢失表达式
请解释我的错误是什么
PS我不知道为什么我无法在这里将查询示例标记为代码。 我为这些查询的可读性差而道歉
您的主要问题是您无法在相同的“嵌套级别”上访问列别名。 为了能够使用别名,您需要将整个查询包装在派生表中:
select *
from (
select t.col1,
t.col2,
(select count(col1)
from tab
where col1 = t.col1
and col2 = t.col2
) as col3
from tab t
)
where col3 > 1
您的“编号”示例不会有两个原因:首先是出于上述原因,其次是因为使用双引号引用的标识符区分大小写。 所以"col3"
是一个与"Col3"
不同的列名。 由于Oracle将不带引号的标识符折叠为大写(符合SQL标准的要求),因此col3
将等效于"COL3"
最后: [col3]
是SQL中的无效标识符,无论您是否将其用作列别名。 必须使用双引号引用标识符。 这些方括号在SQL中无效
您不能在WHERE
子句中使用列别名,只能在ORDER BY
子句中使用。 你有两个选择。
一,您可以将整个查询包装在另一个选择中,然后在col3上过滤:
select * from (
select t.col1,
t.col2,
(select count(col1)
from tab
where col1 = t.col1
and col2 = t.col2
) as col3
from tab t)
where col3 > 1;
或者您可以在WHERE
子句中重复标量子查询:
select t.col1,
t.col2,
(select count(col1)
from tab
where col1 = t.col1
and col2 = t.col2
) as col3
from tab t
where (select count(col1)
from tab
where col1 = t.col1
and col2 = t.col2
) > 1;
我自己建议选项1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.