首页 > 解决方案 > 无法通过子查询按顺序使用数学 - 列不存在

问题描述

我有两个数据表:

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;

我明白了ERROR: column "ranking" does not exist Position: 123

请注意,当不使用子选择时,我可以按排名排序:

select ranking from table_one order by ranking / 1;

在此处复制: http ://sqlfiddle.com/#!17/b88bc/ 12,Postgres 9.6。这是怎么回事?

标签: postgresqlsubquerysql-order-by

解决方案


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

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;

如您所见,使用的排名实际上直接来自 table_one。引擎重新设计了查询以使其正常工作。

想象一下,因为必须在查询的所有计算之后进行别名。在这种情况下,很明显您的 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;

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


推荐阅读