Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PostgreSQL中对两列上的表进行排序,使X列中的值等于上一条记录Y列中的值_Sql_Postgresql - Fatal编程技术网

在PostgreSQL中对两列上的表进行排序,使X列中的值等于上一条记录Y列中的值

在PostgreSQL中对两列上的表进行排序,使X列中的值等于上一条记录Y列中的值,sql,postgresql,Sql,Postgresql,我在PostgreSQL中有一个表,其结构如下: id | from | to ----------+----------+-------- 11 | 18 | 123 3 | 88 | 6 23 | 33 | 18 7 | 123 | 88 我想对该表进行排序,以便给定记录中“from”字段的值等于前一条记录中“to”字段的值

我在PostgreSQL中有一个表,其结构如下:

   id        | from     | to 
----------+----------+--------
    11    | 18       |     123
    3     | 88       |     6
    23    | 33       |     18
    7     | 123      |     88
我想对该表进行排序,以便给定记录中“from”字段的值等于前一条记录中“to”字段的值。换句话说,上述示例在订购时应如下所示:

 id        | from     | to 
----------+----------+--------
    23    | 33       |     18
    11    | 18       |     123
    7     | 123      |     88
    3     | 88       |     6

有人知道如何在PostgreSQL中实现这一点吗?非常感谢。

您可以使用递归CTE来执行此操作,跟踪根目录和级别。以下假设您没有周期:

with recursive t (id, fr, t) as (
      values (11, 18, 123), (3, 88, 6), (23, 33, 18), (7, 123, 88)
     ),
     cte as (
      select t.id, t.fr, t.t, t.fr as root, 1 as lev
      from t
      where not exists (select 1 from t t2 where t2.t = t.fr)
      union all
      select t.id, t.fr, t.t, cte.root, cte.lev + 1
      from t join
           cte
           on t.fr = cte.t
     )
select *
from cte
order by cte.root, cte.lev;

注意:
from
to
是不好的列名,因为它们与SQL关键字冲突。

您好,我确实试过了,效果不错。我不使用“from”和“to”作为列名,这只是为了示例。然而,问题是确实存在周期,如下面的示例所示。您是否知道可以处理循环的解决方案?提前非常感谢。@IliyaMarkov。这回答了您提出的问题。你应该问另一个问题,用合适的数据和你想要如何处理循环的清晰定义。如果你修改了这个问题,你将使这个答案无效,这是粗鲁的,因为它会拉低选票。谢谢你的回答。我将发布一个新问题。