Mar*_*ato 6 sql postgresql postgresql-8.1
我有以下查询:
select
title,
( stock_one + stock_two ) as global_stock
from product
order by
global_stock = 0,
title;
Run Code Online (Sandbox Code Playgroud)
在PostgreSQL 8.1.23中运行它我收到此错误:
查询失败:错误:列"global_stock"不存在
有人可以帮我把它投入使用吗?我首先需要可用的项目,然后是不可用的项目.非常感谢!
Tar*_*ryn 14
你可以ORDER BY这样:
select
title,
( stock_one + stock_two ) as global_stock
from product
order by 2, 1
Run Code Online (Sandbox Code Playgroud)
或将其包装在另一个SELECT中:
SELECT *
from
(
select
title,
( stock_one + stock_two ) as global_stock
from product
) x
order by (case when global_stock = 0 then 1 else 0 end) desc, title
Run Code Online (Sandbox Code Playgroud)
一种解决方案是使用该位置:
select title,
( stock_one + stock_two ) as global_stock
from product
order by 2, 1
Run Code Online (Sandbox Code Playgroud)
但是,别名应该有效,但表达式不一定有效。“global_stock = 0”是什么意思?您的意思是:
select title,
( stock_one + stock_two ) as global_stock
from product
order by (case when global_stock = 0 then 1 else 0 end) desc, title
Run Code Online (Sandbox Code Playgroud)
如果有人在谷歌搜索您是否可以时发现这一点ORDER BY my_alias:是的,您可以。这花了我几个小时。
正如postgres 文档所述:
序数是指输出列的序数(从左到右)位置。此功能使得可以根据没有唯一名称的列定义排序。这并不是绝对必要的,因为总是可以使用该
AS子句为输出列分配名称。
所以要么这个问题已经被修复,要么这个问题专门关于ORDER BY my_alias = 0, other_column我实际上不需要的语法。