使用按查询排序的无序结果

Unordered result using order by query

我正在使用 PostgreSQL 的 pgr_astar 函数来获取最佳路径,我提到结果应该按 seq:

排序
cur.execute("create table %s as SELECT a.seq, a.id1 AS node, a.id2 AS edge, 
b.source, b.target, b.cost, b.reverse_cost, b.km, b.%s, b.%s, b.estimated_time as time, b.ang_elev, b.geom_way
FROM pgr_astar ('SELECT id, source, target, cost as cost, x1, y1, x2, y2, reverse_cost FROM chicago_2po_4pgr', %s, %s, true, true) as a
LEFT JOIN chicago_2po_4pgr as b  ON a.id2 = b.id order by seq    
 " %(nom_table,colonne_cost,colonne_cost_reverse,depart,destination)) 

我得到了这个结果(序列未排序)

0
.
.
124
125
135
136
137
138
139
140
129
130
131
132
133
134

有什么建议吗?我如何修改此查询以获得有序结果。

您是如何查询 行的 table 使用您显示的语句创建的?

虽然显示的查询中的 ORDER BY 应该可以正常工作,但这只是对新创建的 table 中的物理行进行排序。但是行的物理顺序可能会发生变化。 VACUUM 和其他后台进程可以自由地重新排序行。对 table 的任何写访问也将这样做。

此外,更重要的是,SELECT * FROM tbl 未绑定到当前物理顺序 return 行 。虽然 return 按物理顺序排列行通常是最快的方式,而 Postgres 通常会这样做,但没有任何 保证 。您必须附加另一个 ORDER BY 才能获得排序的行(这违背了测试当前物理排序顺序的目的)。

像这样测试行的当前物理顺序

SELECT ctid, * FROM tbl ORDER BY ctid;

ctid 的解释:

并在没有 CREATE TABLE AS 的情况下通过 运行 验证问题中的原始 SELECT,您将看到完美排序的行 ...

相关:

  • Subtract two records of the same column in a table
  • Select last n rows without use of order by clause