考虑PostgreSQL中的以下查询:
SELECT
a, b,
(A VERY LONG AND COMPLICATED SUBQUERY) AS c,
(ANOTHER VERY LONG AND COMPLICATED SUBQUERY) AS d
FROM table
我想在c
子句中设置d
和WHERE
,例如:
WHERE c AND d;
但据我所知,我只能这样做:
WHERE A VERY LONG AND COMPLICATED SUBQUERY) AND
(ANOTHER VERY LONG AND COMPLICATED SUBQUERY)
哪个是笨拙的,代码复制的,breaking the single-choice principle而且非常难看。
顺便说一下,同样的问题也适用于SELECT
子句:我不能将缩写用于先前定义的子查询。
答案 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。
执行此操作