如何在Postgres中使用冗余别名

时间:2018-11-28 12:25:14

标签: sql postgresql

我正在使用来自两个表的联接运行一个查询,这些表具有类似的索引“时间”。我想使用相同的命名索引“时间”返回结果。

SELECT "tbl1"."a"                       "a", 
       "tbl1"."b"                       "b", 
       "tbl2"."c"                       "c", 
       COALESCE("tbl"."time", "tb2"."time") "time" 
FROM   "tbl1" 
       FULL OUTER JOIN "tbl2" 
                    ON "tbl1"."timestamp" = 
                       "tbl2"."timestamp" 
ORDER BY "time"

此查询返回一个错误,指出“时间”是多余的(在ORDER BY中)。

如果我将别名“时间”更改为其他内容,它将起作用。但我确实希望该查询返回“时间”

如果我将ORDER BY更改为

ORDER BY COALESCE("tbl"."time", "tb2"."time")

它也可以工作,但据我所知它将搜索两次Nones并延长执行时间(不是吗?)。

2 个答案:

答案 0 :(得分:3)

您可以使用位置列号代替名称:


SELECT "tbl1"."a"                       "a", 
       "tbl1"."b"                       "b", 
       "tbl2"."c"                       "c", 
       COALESCE("tbl"."time", "tb2"."time") "time" 
FROM   "tbl1" 
       FULL OUTER JOIN "tbl2" 
                    ON "tbl1"."timestamp" = 
                       "tbl2"."timestamp" 
ORDER BY 4;

这同样适用于GROUP BY

答案 1 :(得分:2)

您可以使用横向连接:

SELECT "tbl1"."a"                       "a", 
       "tbl1"."b"                       "b", 
       "tbl2"."c"                       "c", 
       v.time
FROM "tbl1" FULL OUTER JOIN
     "tbl2" 
     ON "tbl1"."timestamp" = "tbl2"."timestamp" CROSS JOIN LATERAL
     (VALUES (COALESCE("tbl"."time", "tb2"."time")) as v(time)
ORDER BY v."time";

我建议您编写查询,以便不需要所有双引号。