這是一個經典的樹路徑表:
CREATE TABLE treepaths(
tpa_ance INTEGER NOT NULL, -- ancestor
tpa_desc INTEGER NOT NULL, -- descendant
tpa_leng INTEGER NOT NULL, -- lenght
UNIQUE(tpa_ance, tpa_desc)
);
初始資料:
1|1|0
1|2|1
1|3|2
1|4|3
1|5|4
1|6|5
2|2|0
2|3|1
2|4|2
2|5|3
2|6|4
3|3|0
3|4|1
3|5|2
3|6|3
4|4|0
4|5|1
4|6|2
5|5|0
5|6|1
6|6|0
我使用以下 SQL 拆分該樹:
DELETE FROM treepaths WHERE tpa_desc IN
(SELECT tpa_desc FROM treepaths WHERE tpa_ance = 4 and tpa_leng <> 0)
AND tpa_ance NOT IN
(SELECT tpa_desc FROM treepaths WHERE tpa_ance = 4 and tpa_leng <> 0);
結果:
1|1|0
1|2|1
1|3|2
1|4|3
2|2|0
2|3|1
2|4|2
3|3|0
3|4|1
4|4|0
5|5|0
5|6|1
6|6|0
作業已經完成,但我想知道是否可以使用 SQLite 撰寫更好的 SQL,從而避免重復相同的代碼:(SELECT tpa_desc FROM treepaths....
在此先感謝您的幫助
uj5u.com熱心網友回復:
您可以做的一種簡化是使用 CTE 而不是子查詢:
WITH cte AS (SELECT tpa_desc FROM treepaths WHERE tpa_ance = 4 and tpa_leng <> 0)
DELETE FROM treepaths
WHERE tpa_desc IN cte AND tpa_ance NOT IN cte;
請參閱演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/497183.html
標籤:sql sqlite 公共表表达式 sql-删除 传递闭包表
下一篇:使用sqlite3時修改的資料
