6

path此查询的结果仅在 order from是preserver时才有意义。但是,在我的左内连接时,结果被打乱了。我在想我可以在结果集中创建一个新列,就像结果的索引一样,然后作为整个 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;
4

1 回答 1

11

要保留返回的订单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;
于 2013-03-05T22:05:29.127 回答