首先,那不是我的桌子。我有一个带有这样的表的项目...
我需要一个想法,以给定的顺序将所有链接的页面/问题放入队列/列表中。
完美的解决方案是:
您知道一种方法(通过内部联接)在一个语句中得到它吗?我的问题是顺序以及两个表之间的混合(合并成一个表)。没关系,如果有2个id字段(每种类型一个),那么我们也可以不使用类型(对于当前元素)。
您可以使用几个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
我使用union all
运算符创建一个组合表,然后将其自身联接:
SELECT id, 'page' AS type, name, next, next_type
FROM page
UNION ALL
SELECT id, 'question', name, next, next_type
FROM question