sqlite CTE with UPDATE(带更新的 sqlite CTE)
问题描述
我希望这不是重复的,我红了一些帖子,但不知道如何解决这个问题.
I hope this is not a duplicate, I red some posts, but could not figure out how to fix this.
我有一张这样的桌子
CREATE TABLE yo (ad INTEGER PRIMARY KEY, pa INTEGER, pd INTEGER);
INSERT INTO yo VALUES
(1,1,1),(2,1,3),(3,1,4),(4,3,5),(5,4,2),(6,3,8),(7,1,9),(8,6,7),(9,3,6);
.header on
.mode column yo
select * from yo;
ad pa pd
---------- ---------- ----------
1 1 1
2 1 3
3 1 4
4 3 5
5 4 2
6 3 8
7 1 9
8 6 7
9 3 6
我可以像这样使用 CTE 创建一个临时表来获取 col 'pd' 的深度级别
I can create a temp table using CTE to obtain the depth level of col 'pd' like this
CREATE table ui AS
WITH RECURSIVE ui(a,l) AS
( VALUES(1,0)
UNION ALL
SELECT yo.ad, ui.l+1
FROM yo JOIN ui ON yo.pa=ui.a
WHERE yo.pa!=yo.ad
ORDER BY 2 desc
)
SELECT a,l FROM ui;
select * from ui;
a l
---------- ----------
1 0
2 1
3 1
4 2
5 3
6 2
8 3
9 2
7 1
然后我想在表 'yo' 中添加一个 col 并在其中输入 th ui.l
Then I want to ADD a col to table 'yo' and enter th ui.l in there
ALTER TABLE yo ADD COLUMN lv INTEGER;
UPDATE yo SET lv=
(SELECT ui.l
FROM ui
WHERE ui.a=yo.ad);
select * from yo;
ad pa pd lv
---------- ---------- ---------- ----------
1 1 1 0
2 1 3 1
3 1 4 1
4 3 5 2
5 4 2 3
6 3 8 2
7 1 9 1
8 6 7 3
9 3 6 2
一切正常.现在我想在 1 个请求中结合临时表ui"创建和表yo"更新?
All works fine. Now I like to combine the temp table 'ui' create and table 'yo' update in 1 request?
我尝试了很多组合回合都找不到解决方案,我确定这很明显,但我不够流利,无法得到它.
I tried many many combanation bout could not find a solution, I sure this is obvious, but I am not fluent enough to get it.
CTE 创建是否应该像
Should the CTE creation be before the UPDATE like in
如何在 SQLite 上使用 CTE 和更新/删除?
或者应该将 CTE 计算到 UPDATE 内的选择中
Or should the CTE be computed into a select inside the UPDATE
感谢任何帮助
干杯,飞
推荐答案
这可行:
WITH RECURSIVE ui(a,l) AS
( VALUES(1,0)
UNION ALL
SELECT yo.ad, ui.l+1
FROM yo JOIN ui ON yo.pa=ui.a
WHERE yo.pa!=yo.ad
ORDER BY 2 desc
)
UPDATE yo SET lv=
(SELECT ui.l
FROM ui
WHERE ui.a=yo.ad);
这也有效:
UPDATE yo SET lv=
(WITH RECURSIVE ui(a,l) AS
( VALUES(1,0)
UNION ALL
SELECT yo.ad, ui.l+1
FROM yo JOIN ui ON yo.pa=ui.a
WHERE yo.pa!=yo.ad
ORDER BY 2 desc
)
SELECT ui.l
FROM ui
WHERE ui.a=yo.ad
);
这篇关于带更新的 sqlite CTE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带更新的 sqlite CTE
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01