postgresql 递归树查询

一、示例数据

  1. CREATE TABLE test
  2. (
  3.   id text,
  4.   pid text,
  5.   msg text
  6. )
  7. insert into test(id,pid,msg) values(‘1’,,’一级(1)’);
  8. insert into test(id,pid,msg) values(‘2’,,’一级(2)’);
  9. insert into test(id,pid,msg) values(‘3’,,’一级(3)’);
  10. insert into test(id,pid,msg) values(‘4’,,’一级(4)’);
  11. insert into test(id,pid,msg) values(’11’,’1′,’二级(1)’);
  12. insert into test(id,pid,msg) values(’22’,’2′,’二级(2)’);
  13. insert into test(id,pid,msg) values(’33’,’3′,’二级(3)’);
  14. insert into test(id,pid,msg) values(’44’,’4′,’二级(4)’);
  15. insert into test(id,pid,msg) values(‘111′,’11’,’三级(1)’);
  16. insert into test(id,pid,msg) values(‘222′,’22’,’三级(2)’);
  17. insert into test(id,pid,msg) values(‘333′,’33’,’三级(3)’);
  18. insert into test(id,pid,msg) values(‘444′,’44’,’三级(4)’);

二、查询

  1. with recursive tmp as
  2. (
  3.   select a.id,a.pid,a.msg from test a where id=’1′
  4.   union all
  5.   select a.id,a.pid,a.msg from test a inner join tmp t on t.id=a.pid
  6. )
  7. select msg from tmp

本文链接地址: postgresql 递归树查询

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注