【问题标题】:Recursive SQLite query递归 SQLite 查询
【发布时间】:2021-04-21 16:29:28
【问题描述】:

我的 SQLite 数据库是这样的:

startn rel endn
immunodeficiencies includes B-cell deficiencies
B-cell deficiencies includes Bruton agammaglobulinemia
immunodeficiencies includes T-cell deficiencies
T-cell deficiencies includes DiGeorge syndrome

还有更多的价值,但这就是要点。

我正在尝试进行递归查询,以获取immunodeficiencies 的所有终端子节点。即,对于这个例子,我想Bruton agammaglobulinemia, DiGeorge syndrome

基于another answer,这是我目前所拥有的,但它不起作用:

with recursive tc( i )
  as ( select endn from dx_graph where startn = 'immunodeficiencies' and rel = 'includes'
        union endn from dx_graph, tc where startn = tc.i and rel = 'includes'
     )
 select * from tc;

样本数据:

CREATE TABLE "dx_graph" (
    "startn"    TEXT,
    "rel"   TEXT,
    "endn"  TEXT,
)

insert into dx_graph values ('immunodeficiencies', 'includes', 'B-cell deficiencies')
insert into dx_graph values ('immunodeficiencies', 'includes', 'T-cell deficiencies')
insert into dx_graph values ('immunodeficiencies', 'includes', 'complement disorders')
insert into dx_graph values ('B-cell deficiencies', 'includes', 'Bruton agammaglobulinemia')
insert into dx_graph values ('T-cell deficiencies', 'includes', 'DiGeorge syndrome')
insert into dx_graph values ('complement disorders', 'includes', 'C1 esterase inhibitor deficiency')
insert into dx_graph values ('complement disorders', 'includes', 'C5-C9 deficiency')

【问题讨论】:

  • 我知道我真正想要的是一个图形数据库,但老实说我试过 Neo4J,它插入新值实在是太笨重了。
  • 请定义“子节点”的含义。期望的结果会有所帮助。
  • 刚刚添加,谢谢
  • 请以纯文本形式提供示例数据,最好是创建表和插入语句,以便轻松导入测试数据库。

标签: sql sqlite recursion


【解决方案1】:

您的递归查询将找到原始指定父节点的所有子节点;然后,您需要根据它们是否有任何子节点来过滤它们。您可以使用NOT EXISTS 子句来做到这一点:

WITH RECURSIVE tc AS (
  SELECT endn
  FROM dx_graph 
  WHERE startn = 'immunodeficiencies' AND rel = 'includes'
  UNION ALL
  SELECT dx.endn
  FROM dx_graph dx
  JOIN tc ON dx.startn = tc.endn AND dx.rel = 'includes'
)
SELECT endn
FROM tc
WHERE NOT EXISTS (
  SELECT *
  FROM dx_graph dx
  WHERE dx.startn = tc.endn AND dx.rel = 'includes'
)

输出(针对有问题的样本数据):

endn
Bruton agammaglobulinemia
DiGeorge syndrome
C1 esterase inhibitor deficiency
C5-C9 deficiency

Demo on db-fiddle

NOT EXISTS 子句从递归 CTE 中过滤掉任何具有子节点的节点(即 CTE 中的 endn 值与具有 rel='includes' 的原始表中的 startn 值匹配)。这样你只能得到终端节点,因为它们没有子节点。

【讨论】:

  • 这行得通!太感谢了。现在我将尝试了解它是如何工作的。非常感谢您的回答/解释!
  • @pls_have_mercy_i_am_a_noob 不用担心 - 我很高兴能帮上忙。基本上这是可行的,因为 NOT EXISTS 子句从递归 CTE 中过滤掉任何具有子节点的节点(即 CTE 中的 endn 值与具有 rel='includes' 的原始表中的 startn 值匹配)。这样你只能得到终端节点,因为它们没有子节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多