postgresql - 无法通过子查询按顺序使用数学 - 列不存在
问题描述
我有两个数据表:
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。这是怎么回事?
解决方案
您的问题是您的“排名”是一个错误:
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;
还有一点建议:如果可以在查询的选择部分运行子查询,请避免。如果您的引擎找不到正确重写查询的方法,则需要为您的引擎处理大量工作。想象一下,它对查询的第一个结果的每个结果行进行一个新查询。当然也有例外,但在做之前要考虑清楚,并为自己证明为什么使用它来代替适当的连接。
推荐阅读
- python - 运行 python manage.py makemigrations 的问题
- java - 将 0 翻转为 1 的 Java 代码
- java - 在 web 元素中查找动态样式属性
- sql - Oracle 11g:是否可以创建聚集唯一索引?
- python - 错误“Service.py”
- solr - 使用 Solr 进行拼写检查
- java - 如何在 Spring MVC 中使 jsonData 不区分大小写
- vb.net - 如何将事件处理程序移动到父表单并传递 eventargs
- python - Python prgram 重命名后不会构建
- javascript - 如何创建一个 foreach 循环以将音节放置在其各自单词的每个输入中