以下查询正常工作:
SELECT a, b, c,
(SELECT COUNT(*) AS COUNT FROM table_b WHERE field_a = p.a) AS d
FROM table_a AS p
ORDER BY b DESC
这也有效:
SELECT a, b, c,
(SELECT COUNT(*) AS COUNT FROM table_b WHERE field_a = p.a) AS d
FROM table_a AS p
ORDER BY d DESC
但是以下内容会产生ERROR; column 'd' does not exist
错误:
SELECT a, b, c,
(SELECT COUNT(*) AS COUNT FROM table_b WHERE field_a = p.a) AS d
FROM table_a AS p
ORDER BY (b * d) DESC
上述三个查询之间的唯一区别是ORDER BY
子句。在前两个查询中,结果按b
字段或动态d
字段排序。在上一个查询中,结果(应该)按b
次d
的乘积排序。
为什么在上一个查询中,PostgreSQL说d
不存在,而它可以在第二个查询中找到它而没有问题?
答案 0 :(得分:1)
order by
clause中的任意表达式只能由输入列构成:
每个表达式可以是输出列的名称或序号(SELECT列表项),也可以是由输入列值组成的任意表达式。
你需要对它进行子查询:
select *
from (select 1 as a, 2 as b) s
order by a * b