![](/img/trans.png)
[英]I have a SQL query with a Union. I need only include data in second query if field in first query does not include result from column
[英]SQL Tree Query - WITH RECURSIVE & UNION. How to sort by a second value
我有一個具有樹狀結構的類別表(見下圖)。 對於快速的單個查詢,我有以下 SQL 來獲取完整的樹。
WITH RECURSIVE search_tree(id, name, path, position) AS
(
SELECT id, name, ARRAY[id], position
FROM table_name
WHERE id = id
UNION ALL
SELECT table_name.id, table_name.name, path || table_name.id,
table_name.position
FROM search_tree
JOIN table_name ON table_name.parent_id = search_tree.id
WHERE NOT table_name.id = ANY(path)
)
SELECT id, name, path, position
FROM search_tree
ORDER BY path
此查詢結果如下表
id | name | path | position
----+--------------+---------+-------------
1 | Cat Pictures | {1}. |. 0
2 | Funny | {1,2}. |. 0
3 | LOLCats | {1,2,3} |. 1
4 | Animated | {1,2,4} |. 2
5 | Classic | {1,2,5} |. 0
6 | Renaissance | {1,6} |. 1
所以根據路徑排序效果很好。 但我需要的是根據列 position 的順序,如果路徑級別是同一級別(如 id 2 和 4,以及 3、4、5)。
因此 ID 的順序是
ids: 1, 6, 2, 5, 3, 4
如何更改我的 SQL 聲明以反映該訂單?
可以這樣實現https://www.db-fiddle.com/f/rpFiPjKSwHW88C4cp6o9Rm/0
with recursive search_tree(id, parentPath, name) as (
select id, cast(row_number() over(order by pos) as text), name
from objects
where parent_id = 0
union all
select o.id, concat(search_tree.parentPath, ',', cast(row_number() over(order by o.pos) as text)), o.name
from search_tree
join objects as o on search_tree.id = o.parent_id
)
select *
from search_tree
order by parentPath;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.