递归查询

时间:2015-04-20 11:29:44

标签: mysql recursion

我遇到递归查询问题: 表partlist中有两个字段:articlepart。一篇文章可以有多个部分,一部分也可以有其他部分。

例如:

  • Article 0包含部​​分article 1article 2
  • Article 1包含部​​分article 1aarticle 1b
  • Article 2包含部​​分article 1aarticle 2b
  • Article 2b包含部​​分article 3aarticle 3b

我把它放在SQL中:

With list as 
(select article,part from partlist as e
union all
select article,part from partlist as e inner join liste as l on e.article=l.part)

select article, part from list

看起来很好:

article    | part
-----------+-----------
Article 1  | article 1a 
Article 1  | article 1b
Article 2  | article 1a 
Article 2  | article 2b 
article 2b | article 3a 
article 2b | article 3b

但现在我想把两种行号放在上面。一个用于所有行,一个用于父行。 它应该是这样的:

row | parent row | article    | part
----+------------+------------+-----------
0   | null       | Article 0  | article 1
1   | null       | Article 0  | article 2
2   | 0          | Article 1  | article 1a 
3   | 0          | Article 1  | article 1b
4   | 1          | Article 2  | article 1a 
5   | 1          | Article 2  | article 2b 
6   | 5          | article 2b | article 3a 
7   | 5          | article 2b | article 3b 

我尝试了row_number,但这不是正确的sql查询。

0 个答案:

没有答案