PostgreSQL:在WHERE子句中使用子查询缩写('AS')

时间:2010-01-27 10:31:50

标签: postgresql sql

考虑PostgreSQL中的以下查询:

SELECT 
    a, b, 
   (A VERY LONG AND COMPLICATED SUBQUERY) AS c,
   (ANOTHER VERY LONG AND COMPLICATED SUBQUERY) AS d
FROM table

我想在c子句中设置dWHERE,例如:

WHERE c AND d;

但据我所知,我只能这样做:

WHERE A VERY LONG AND COMPLICATED SUBQUERY) AND 
   (ANOTHER VERY LONG AND COMPLICATED SUBQUERY)

哪个是笨拙的,代码复制的,breaking the single-choice principle而且非常难看。

顺便说一下,同样的问题也适用于SELECT子句:我不能将缩写用于先前定义的子查询。

1 个答案:

答案 0 :(得分:12)

您可以使用子查询:

SELECT a,b,c,d FROM
    (SELECT 
        a, b, 
        (A VERY LONG AND COMPLICATED SUBQUERY) AS c,
        (ANOTHER VERY LONG AND COMPLICATED SUBQUERY) AS d
        FROM table
    ) AS T1
WHERE c AND d

您也可以使用CTE

执行此操作