只有来自path
的订单是保留者时,此查询的结果才有意义。但是,在我的Left Inner Join中,结果是混乱的。我想我可以在结果集中创建一个新列,就像结果的索引一样,然后作为整个sql的最后一个子句添加一个ORDER BY idx
。
这是我的查询而不是试图保留最终订单:
SELECT path.*, network_link.v0prt
FROM (SELECT * // Need order preserved from this one
FROM shortest_path_shooting_star(
'SELECT gid as id, source::integer,
target::integer, distance::double precision as cost,
x1, y1, x2, y2, rule, to_cost FROM
network_link as net ORDER BY net.gid', 9, 1, false, false)) as path
LEFT OUTER JOIN
(SELECT DISTINCT gid, v0prt FROM network_link) as network_link
ON (network_link.gid=path.edge_id);
任何见解都会很棒。
感谢。 我尝试添加索引值和ORDER BY(不起作用)。
SELECT path.*, network_link.v0prt
FROM (SELECT incr(0) as idx, *
FROM shortest_path_shooting_star(
'SELECT gid as id, source::integer,
target::integer, distance::double precision as cost,
x1, y1, x2, y2, rule, to_cost FROM
network_link as net ORDER BY net.gid', 9, 1, false, false)) as path
LEFT OUTER JOIN
(SELECT DISTINCT gid, v0prt FROM network_link) as network_link
ON (network_link.gid=path.edge_id)
ORDER BY idx;
答案 0 :(得分:10)
要保留shortest_path_shooting_star
返回的顺序(如果不提供其他方式),您可以使用窗口函数row_number
来跟踪原始顺序,并ORDER BY
结果:
SELECT path.*, network_link.v0prt
FROM (SELECT row_number() OVER() AS row_number, *
FROM shortest_path_shooting_star(
'SELECT gid as id, source::integer,
target::integer, distance::double precision as cost,
x1, y1, x2, y2, rule, to_cost FROM
network_link as net ORDER BY net.gid', 9, 1, false, false)) as path
LEFT OUTER JOIN
(SELECT DISTINCT gid, v0prt FROM network_link) as network_link
ON (network_link.gid=path.edge_id)
ORDER BY path.row_number;
<强>更新强>
从PostgreSQL版本9.4及更新版本开始,更好的方法是使用WITH ORDINALITY
:
SELECT path.*, network_link.v0prt
FROM shortest_path_shooting_star(
'SELECT gid as id, source::integer,
target::integer, distance::double precision as cost,
x1, y1, x2, y2, rule, to_cost FROM
network_link as net ORDER BY net.gid', 9, 1, false, false)
) WITH ORDINALITY AS path
LEFT OUTER JOIN
(SELECT DISTINCT gid, v0prt FROM network_link) as network_link
ON (network_link.gid=path.edge_id)
ORDER BY path.ordinality;