简体   繁体   English

DB2子句在where子句中查询别名

[英]DB2 sql queries alias in where clause

Is there a way where we could query using aliases 有没有办法我们可以使用别名查询

SELECT 
   'X' AS AVC
 FROM 
   sysibm.sysdummy1
 WHERE AVC= 'X'

I am just looking for a way , I could query for alias column. 我只是在寻找一种方法,我可以查询别名列。

I am getting the below error. 我收到以下错误。

Error: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=AVC, 
DRIVER=3.63.75
SQLState:  42703
ErrorCode: -206
Error: DB2 SQL Error: SQLCODE=-514, SQLSTATE=26501, SQLERRMC=SQL_CURLH200C1, 
DRIVER=3.63.75
SQLState:  26501
ErrorCode: -514

Any input would be helpful ! 任何输入都会有所帮助!

Thanks ! 谢谢 !

you can't use alias in where condition because the sql engine eval the query clause (FROM, WHERE, SELECT...) in a specific order and the select clause in evaluated after the where clause 你不能在where条件中使用别名,因为sql引擎按特定顺序评估查询子句(FROM,WHERE,SELECT ...),并在where子句之后评估select子句

so at the moment of the where evalution the column alias in not know by th db engine 所以在评估的时刻,列别名不是由数据库引擎知道的

You must repeat the code 您必须重复该代码

SELECT 'X' AS AVC
FROM  sysibm.sysdummy1
WHERE X' = 'X' 

You can't. 你不能。 This is a general rule of SQL. 这是SQL的一般规则。 In practice, you can think of the reason being that the where is parsed before the select , so the aliases are not known. 在实践中,您可以想到在select之前解析where的原因,因此别名是未知的。

The general solution is to use a subquery or CTE: 一般的解决方案是使用子查询或CTE:

SELECT t.*
FROM (SELECT 'X' AS AVC
      FROM sysibm.sysdummy1
     ) t
WHERE AVC = 'X';

My preferred solution is to use a lateral join, but I don't think DB2 supports either APPLY or LATERAL . 我首选的解决方案是使用横向连接,但我不认为DB2支持APPLYLATERAL

The engine does not know of table or column aliases until it is finished gathering the data. 在完成数据收集之前,引擎不知道表或列别名。 You can use them in ORDER BY statement within the same query but that's it. 您可以在同一查询中的ORDER BY语句中使用它们,但就是这样。 You can however, use a Common Table Expression also known as a CTE : 但是,您可以使用Common Table Expression也称为CTE

WITH myCTE AS (
SELECT 'X' AS AVC
 FROM sysibm.sysdummy1
)
SELECT *
  FROM myCTE
    WHERE AVC= 'X'

This is somewhat of a long way to do it but unfortunately that is it. 这是一个很长的路要走但不幸的是就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM