[英]Recursive SQL query on a tree with stop condition to stop digging in the sub tree
[英]Recursive SQL query on nested-set tree with stop condition
示例數據如下所示:
+----+-----------+------+-------+-----------------+
| id | parent_id | left | right | stop_descending |
+----+-----------+------+-------+-----------------+
| 1 | NULL | 1 | 10 | 0 |
| 2 | 1 | 2 | 3 | 0 |
| 3 | 1 | 4 | 9 | 1 |
| 4 | 3 | 5 | 6 | 0 |
| 5 | 3 | 7 | 8 | 0 |
+----+-----------+------+-------+-----------------+
獲取整棵樹非常簡單:
SELECT t0.*
FROM nested_set AS t0
LEFT JOIN nested_set AS t1 ON t0.left BETWEEN t1.left AND t1.right
WHERE t1.parent_id IS NULL
ORDER BY t0.left;
但是,我想獲取其父節點沒有 stop_ 降序標志的所有節點。 結果應包括節點 1、2、3。 節點 4,5 應該被排除在外,因為它們的父節點具有 stop_Descing 標志。 如果節點 4 和 5 有子節點,則也應排除這些子節點。 一旦 is_leaf 值等於 1,遞歸應該停止。
我嘗試了許多不同的方法,但從未得到正確的結果。 我正在 MariaDB 10.1.26 中運行查詢。 也許有更好的解決方案涉及更高版本的 CTE。
您執行另一個自連接以檢查該葉子是否是stop_decending = 1
的節點的一部分
SELECT t0.*, t1.*, t3.*
FROM nested_set AS t0
LEFT JOIN nested_set AS t1
ON t0.left BETWEEN t1.left AND t1.right
LEFT JOIN nested_set as t3
ON t0.id BETWEEN t3.left AND t3.right
AND t3.stop_descending = 1
WHERE t1.parent_id IS NULL
AND t3.id IS NULL
ORDER BY t0.left;
輸出
| id | parent_id | left | right | stop_descending | id | parent_id | left | right | stop_descending | id | parent_id | left | right | stop_descending |
|----|-----------|------|-------|-----------------|----|-----------|------|-------|-----------------|--------|-----------|--------|--------|-----------------|
| 1 | (null) | 1 | 10 | 0 | 1 | (null) | 1 | 10 | 0 | (null) | (null) | (null) | (null) | (null) |
| 2 | 1 | 2 | 3 | 0 | 1 | (null) | 1 | 10 | 0 | (null) | (null) | (null) | (null) | (null) |
| 3 | 1 | 4 | 9 | 1 | 1 | (null) | 1 | 10 | 0 | (null) | (null) | (null) | (null) | (null) |
對於調試注釋過濾器AND t3.id IS NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.