SQLITE 中的两个递归选择联合
Posted
技术标签:
【中文标题】SQLITE 中的两个递归选择联合【英文标题】:TWO RECURSIVE SELECTS UNION IN SQLITE 【发布时间】:2020-12-15 10:05:26 【问题描述】:我想问一个问题,我怎样才能将这两个递归 SELECTS 合并到一个结果集中。谢谢你的回答
WITH sub_tree (Item_id,Item_name,Item_fyz,Item_fyz_hodnotaID)
AS
(Select A.id,A.name,A.fyz1_x_id,A.fyz_hodnota_id
from fyz_hodnota AS A
where A.id = 29
UNION ALL
SELECT BF.id, BF.name,BF.fyz1_x_id, BF.fyz_hodnota_id
from fyz_hodnota AS BF
inner join sub_tree st on st.Item_id = BF.fyz_hodnota_id)
SELECT DISTINCT * from sub_tree
WITH sub_tree (Item_id,Item_name,Item_fyz,Item_fyz_hodnotaID)
AS
(Select A.id,A.name,A.fyz1_x_id,A.fyz_hodnota_id
from fyz_hodnota AS A
where A.id=27
UNION ALL
SELECT BF.id, BF.name,BF.fyz1_x_id, BF.fyz_hodnota_id
from fyz_hodnota BF
inner join sub_tree st on st.Item_fyz_hodnotaID = BF.id)
SELECT * from sub_tree
【问题讨论】:
请不要大喊大叫 【参考方案1】:在同一 WITH
子句下声明 2 个 CTE 并应用 UNION
:
WITH
sub_tree1(Item_id,Item_name,Item_fyz,Item_fyz_hodnotaID) AS (
Select A.id,A.name,A.fyz1_x_id,A.fyz_hodnota_id
from fyz_hodnota AS A where A.id = 29
UNION ALL
SELECT BF.id, BF.name,BF.fyz1_x_id, BF.fyz_hodnota_id
from fyz_hodnota AS BF inner join sub_tree1 st
on st.Item_id = BF.fyz_hodnota_id
),
sub_tree2(Item_id,Item_name,Item_fyz,Item_fyz_hodnotaID) AS (
Select A.id,A.name,A.fyz1_x_id,A.fyz_hodnota_id
from fyz_hodnota AS A
where A.id=27
UNION ALL
SELECT BF.id, BF.name,BF.fyz1_x_id, BF.fyz_hodnota_id
from fyz_hodnota BF inner join sub_tree2 st
on st.Item_fyz_hodnotaID = BF.id
)
SELECT DISTINCT * from sub_tree1
UNION ALL
SELECT * from sub_tree2
【讨论】:
以上是关于SQLITE 中的两个递归选择联合的主要内容,如果未能解决你的问题,请参考以下文章
从 MS-Access 中联合选择查询中的 SQLite 语法错误