Postgresql 无法将数学按顺序与子查询一起使用-列不';不存在

Postgresql 无法将数学按顺序与子查询一起使用-列不';不存在,postgresql,subquery,sql-order-by,Postgresql,Subquery,Sql Order By,我有两个数据表: create table table_one (table_two_id integer, ranking numeric); create table table_two (id integer); insert into table_one (table_two_id, ranking) values (1, 5); insert into table_one (table_two_id, ranking) values (2, 10); insert into tab

我有两个数据表:

create table table_one (table_two_id integer, ranking numeric);
create table table_two (id integer);

insert into table_one (table_two_id, ranking) values (1, 5);
insert into table_one (table_two_id, ranking) values (2, 10);

insert into table_two (id) values (1);
insert into table_two (id) values (2);
我可以这样查询和订购:

select 
  (select ranking from table_one where table_two_id = tbl_2.id) as ranking,
  id
from table_two as tbl_2 order by ranking desc;
但是如果我想用一点数学知识来修改
order by
查询:

select 
  (select ranking from table_one where table_two_id = tbl_2.id) as ranking,
  id
from table_two as tbl_2 order by ranking * 1 desc;
我得到
错误:列“排名”不存在位置:123

请注意,在不使用subselect时,我可以通过排名进行排序:

select ranking from table_one order by ranking / 1;

此处复制:,博士后9.6。发生了什么事?

你的问题是你的“排名”是一个错误:

select 
  tbl_1.ranking,
  id
from table_two as tbl_2 
  inner join table_one as tbl_1
  on tbl_1.table_two_id = tbl_2.id
order by tbl_1.ranking * 1 desc;
您可以通过运行以下查询来确保:

select 
  (select ranking from table_one where table_two_id = tbl_2.id),
  id
from table_two as tbl_2 
order by ranking desc;
正如您所看到的,所使用的排名实际上直接来自表1。引擎重新设计了查询以使其正常工作

想象一下这一点,因为别名必须在查询的所有计算之后进行。在这种情况下,很明显,order by找不到尚未命名的列

您可以验证以下内容:

with cte as 
(
select 
  (select ranking from table_one where table_two_id = tbl_2.id) as ranking,
  id
from table_two as tbl_2 
)
select *
from cte
order by ranking *1 desc;

还有一点建议:如果可以在查询的select部分运行子查询,请避免。如果您的引擎找不到正确重写查询的方法,则需要处理大量的工作。想象一下,它为您的查询的第一个结果的每个resultat行执行一个新的查询。当然也有例外,但在做之前要仔细考虑一下,并向自己证明为什么要用它来代替正确的连接。

感谢您的详细回复。我知道Postgres会尝试将subselect改为联接,以提高效率,但我不明白为什么这会导致
按排名*1排序失败,因为联接可以按
排名和
排名*1
排序。我遗漏了什么?事实上有一个解释,但似乎很古老:(引用)ORDER BY(以及GROUP BY)只允许在输出列名未经修饰时引用它们。不能在表达式中使用它们。这是SQL92和SQL99规则之间的折衷。。。这有点难看(引用结束)。