---
title: "db2还是蛮强的"
author: "jedy"
date: "2005-12-08T03:06:00Z"
tags: []
slug: "db2"
draft: false
lastmod: "2005-12-08T03:06:00Z"
id: 304757
url: "https://jedy.iteye.com/blog/304757"
---

开始看db2 cookbook，以前一直用MySQL，现在发现它的功能还是太少了。

一个树形表，

ID          PID         NAME  
\----------- ----------- ----------  
          1           1 a  
          2           2 b  
          3           1 c  
          4           1 d  
          5           3 e  
          6           5 f  
要把同一枝一次取出来，利用db2中的递归，很容易就可以实现。

> with tmp (id) as (  
>     select id from test where pid = 1 and id = pid  
>     union all  
>     select [test.id](http://test.id) from test,tmp where test.pid = [tmp.id](http://tmp.id) and [test.id](http://test.id) &lt;&gt; [tmp.id](http://tmp.id)  
> )  
> select * from test where id in (select id from tmp)

 

ID          PID         NAME  
\----------- ----------- ----------  
          1           1 a  
          3           1 c  
          4           1 d  
          5           3 e  
          6           5 f