(?) SQL - 互连连接(如何在两个表之间建立链?)

(?) SQL - interlinked joins (how to build a chain between two tables?)

首先,那不是我的table。我有一个这样的项目 tables...

我需要一个想法,以给定的顺序在 queue/list 中获取所有链接的 pages/questions。

完美的解决方案是:

您知道在一个语句中(通过内部联接)获得它的方法吗? 我的问题是顺序以及两个 table 之间的混合,合并为一个。 也可以,如果有 2 个 id 字段(每个类型一个),那么我们也可以不使用类型(对于当前元素)。

我使用 union all 运算符创建组合 table,然后将其加入自身:

SELECT id, 'page' AS type, name, next, next_type
FROM   page
UNION ALL
SELECT id, 'question', name, next, next_type
FROM question

您可以使用几个 CTE 来首先 UNION 将表格放在一起,然后从 firstPage 开始查看列表,使用行号来保证顺序结果数:

WITH allpq AS (
  SELECT name, 'page' AS type, next, next_type
  FROM page
  UNION ALL 
  SELECT name, 'question', next, next_type
  FROM question
),
list AS (
  SELECT type, name, next, next_type, 1 as rn
  FROM allpq
  WHERE name = 'firstPage'
  UNION ALL
  SELECT a.type, a.name, a.next, a.next_type, list.rn + 1
  FROM allpq a
  JOIN list ON a.name = list.next AND a.type = list.next_type
)
SELECT type, name, next, next_type
FROM list
ORDER BY rn

输出:

type        name            next            next_type
page        firstPage       secondPage      page
page        secondPage      firstQuestion   question
question    firstQuestion   secondQuestion  question
question    secondQuestion  thirdPage       page
page        thirdPage       fourthPage      page
page        fourthPage      fourthQuestion  question
question    fourthQuestion  fifthPage       page
page        fifthPage       fifthQuestion   question
question    fifthQuestion   sixthPage       page
page        sixthPage       seventhPage     page
page        seventhPage     eighthPage      page
page        eighthPage      

Demo on dbfiddle