Understanding Oracle aliasing - why isn't an alias not recognized in a query unless wrapped in a second query?

こ雲淡風輕ζ 提交于 2019-12-23 08:50:47

问题


I have a query


SELECT COUNT(*) AS "CNT",
       imei
FROM   devices  

which executes just fine. I want to further restrict the query with a WHERE statement. The (humanly) logical next step is to modify the query followingly:


SELECT COUNT(*) AS "CNT",
       imei
FROM   devices
WHERE  CNT > 1 

However, this results in a error message ORA-00904: "CNT": invalid identifier. For some reason, wrapping the query in another query produces the desired result:


SELECT *
FROM   (SELECT COUNT(*) AS "CNT",
               imei
        FROM   devices
        GROUP  BY imei)
WHERE  CNT > 1  

Why does Oracle not recognize the alias "CNT" in the second query?


回答1:


The simple answer is that the AS clause defines what the column will be called in the result, which is a different scope than the query itself.

In your example, using the HAVING clause would work best:

SELECT COUNT(*) AS "CNT",
       imei
FROM   devices
GROUP  BY imei
HAVING COUNT(*) > 1



回答2:


Because the documentation says it won't:

Specify an alias for the column expression. Oracle Database will use this alias in the column heading of the result set. The AS keyword is optional. The alias effectively renames the select list item for the duration of the query. The alias can be used in the order_by_clause but not other clauses in the query.

However, when you have an inner select, that is like creating an inline view where the column aliases take effect, so you are able to use that in the outer level.




回答3:


I would imagine because the alias is not assigned to the result column until after the WHERE clause has been processed and the data generated. Is Oracle different from other DBMSs in this behaviour?




回答4:


To summarize, this little gem explains:

10 Easy Steps to a Complete Understanding of SQL

A common source of confusion is the simple fact that SQL syntax elements are not ordered in the way they are executed. The lexical ordering is:

SELECT [ DISTINCT ]
FROM
WHERE
GROUP BY
HAVING
UNION
ORDER BY

For simplicity, not all SQL clauses are listed. This lexical ordering differs fundamentally from the logical order, i.e. from the order of execution:

FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
UNION
ORDER BY

As a consequence, anything that you label using "AS" will only be available once the WHERE, HAVING and GROUP BY have already been performed.



来源:https://stackoverflow.com/questions/6153778/understanding-oracle-aliasing-why-isnt-an-alias-not-recognized-in-a-query-unl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!