SQL Lite中的递归查询CTE

时间:2015-05-15 12:54:14

标签: sqlite recursive-query

我有下表结构。 (我是SQL Lite的新手)

create table Relations 
(
Code int,
ParentCode int ,
fname text
)
GO
insert into Relations values(1,null,'A');
insert into Relations values(2,null,'B');
insert into Relations values(3,2,'C');
insert into Relations values(4,3,'D');

我想得到Code = 4的初始父代: 即值2无效B

我无法弄清楚如何在sqllite中编写递归查询。 在此先感谢..

1 个答案:

答案 0 :(得分:0)

版本问题.. 此查询无效&得到了语法错误。 我从3.7.17升级到3.8.7.4版本&它工作..

WITH RECURSIVE
  works(Code,Parent) AS (
   Select Code,ParentCode from Relations a where a.Code=4
    UNION
    SELECT Relations.Code, Relations.ParentCode FROM Relations , works
     WHERE Relations.Code=works.Parent
  )
SELECT * FROM works where Parent is null