Вы можете использовать пару 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
Демонстрация на dbfiddle