【问题标题】:Sqlite query to get the all child and sub-child by the parent id from two tables:Sqlite 查询通过父 id 从两个表中获取所有子和子:
【发布时间】:2019-09-10 07:28:42
【问题描述】:

我有两张桌子,例如。

表1

id  title 
1   t1
2   t2
3   t3
4   t4
5   t5
6   t6
7   t7

表2

id  tid  parent_id
1    2   1
2    3   1
3    4   2
4    5   3
5    7   6

我通过与父 id 的内部联接仅获得一个级别的结果,查询是:

SELECT id,title
from table1 INNER JOIN
     table2
     ON table2.tid = table1.id
where table2.parent_id = 1

我只想输出父ID的所有孩子和子孩子。 假设在这里我只想要父 id 1 的所有子项和子项,然后输出将出现,例如:

输出

id title
2   t2
3   t3
4   t4
5   t5

因为 t2,t3 父 id 为 1,t4,t5 在 2 之下,2 在 1 父 id 之下,t3 也是。

所以我想要所有的孩子和子孩子的父母 id。

如果您有任何困惑,请告诉我,谢谢

【问题讨论】:

标签: sql sqlite


【解决方案1】:

你想要一个递归 CTE:

with recursive cte as (
      select t2.tid
      from table2 t2
      where t2.parent_id = 1
      union all
      select t2.tid
      from cte join
           table2 t2
           on t2.parent_id = cte.tid
     )
select t1.*
from cte join
     table1 t1
     on t1.id = cte.tid;

【讨论】:

  • 是否有可能没有递归函数,因为当我使用这个显示错误的离子 sqlite 但是当我在本地系统上使用它时工作正常。并且简单的查询和连接在 ionic sqlite 中运行良好,但我猜递归函数存在问题。
  • @shivchauhan 。 . .可能需要关键字recursive
  • 我使用了递归但仍然显示错误! ;)
【解决方案2】:

查找顶级项目的所有后代

with recursive hier(topid, tid, parent_id, level) as(
  select t1.id topid, t1.id tid, null parent_id, 1 level
  from Table1 t1
  where not exists(select 1 from Table2 where tid = t1.id)
  union all
  select h.topid, t2.tid, h.tid, level+1
  from hier h 
  join Table2 t2 on h.tid = t2.parent_id
  order by level desc
) 
select  h.topid parent, h.tid descendant, t.title, h.level
from hier h
join Table1 t on t.id = h.tid 
where level > 1;

Fiddle

【讨论】:

  • 非常感谢您的努力@serg
猜你喜欢
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 2018-04-19
  • 2022-11-20
相关资源
最近更新 更多