如何在PostgreSQL ORDER BY子句中使用ALIAS?

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)

  • @Noobgrammer Yuck,这是一个非常古老的答案,我不会再建议“按 2, 1 排序”。:) (2认同)
  • @bluefeet 好的。谢谢你。我认为无论如何都行不通。我认为 `COALESCE(2, 1)` 的计算结果始终为 `2`,使其等同于 `ORDER BY 2`。总之,别介意。就我而言,我认为将 `COALESCE(MAX(c.created), p.created) AS posted_at` 添加到 `SELECT` 之后的列列表中,然后添加 `ORDER BY Posted_at DESC` 实际上效果更好。 (2认同)

Gor*_*off 5

一种解决方案是使用该位置:

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)


Fol*_*ten 5

如果有人在谷歌搜索您是否可以时发现这一点ORDER BY my_alias:是的,您可以。这花了我几个小时。

正如postgres 文档所述:

序数是指输出列的序数(从左到右)位置。此功能使得可以根据没有唯一名称的列定义排序。这并不是绝对必要的,因为总是可以使用该AS子句为输出列分配名称。

所以要么这个问题已经被修复,要么这个问题专门关于ORDER BY my_alias = 0, other_column我实际上不需要的语法。