2013-03-14 155 views
0

我只有一個表 「tbl_test」PL SQL查詢recuresive循環

其中有表提起低於

tbl_test table 
trx_id | proj_num | parent_num| 
1  | 14  | 0   | 
2  | 14  | 1   | 
3  | 14  | 2   | 
4  | 14  | 0   | 
5  | 14  | 3   | 
6  | 15  | 0   | 

結果,我想給出的是:當trx_id值5被取出

這是一個父母子女關係。所以,

trx_id -> parent_num 
5  -> 3 
3  -> 2 
2  -> 1 

這意味着輸出值:

3 
2 
1 

讓所有父鏈

查詢我所用:

SELECT * FROM ( 
    WITH RECURSIVE tree_data(project_num, task_num, parent_task_num) AS( 
    SELECT project_num, task_num, parent_task_num 
      FROM tb_task 
      WHERE project_num = 14 and task_num = 5 
      UNION ALL 
      SELECT child.project_num, child.task_num, child.parent_task_num 
       FROM tree_data parent Join tb_task child 
       ON parent.task_num = child.task_num AND parent.task_num = child.parent_task_num 
      ) 
      SELECT project_num, task_num, parent_task_num 
      FROM tree_data 
      ) AS tree_list ; 

任何人可以幫助我嗎?

+0

看看遞歸的CTE('WITH RECURSIVE'查詢)。 – 2013-03-14 12:24:04

+0

檢查但令人困惑... – 2013-03-14 12:28:57

+0

Mysql不支持WITH,所以最好試試這個, http://stackoverflow.com/questions/1382573/how-do-you-use-the-with-clause -in-mysql – Balamurugan 2013-03-14 12:29:16

回答

1

沒有必要使用pl/pgsql來做到這一點。你可以直接在SQL中完成。試想一下:

WITH RECURSIVE my_tree AS (
    SELECT trx_id as id, parent_id as parent, trx_id::text as path, 1 as level 
     FROM tbl_test 
     WHERE trx_id = 5 -- start value 
    UNION ALL 
    SELECT t.trx_id, t.parent_id, p.path || ',' || t.trx_id::text, p.level + 1 
     FROM my_tree p 
     JOIN tbl_text t ON t.trx_id = p.parent 
) 
select * from my_tree; 
+0

此查詢繼續運行。不停止並拋出輸出 – 2013-03-14 12:56:53

+0

是否有可能您有層次循環?如果你想看看它返回的是什麼,請添加到my_tree中的第二個SELECT中,WHERE level <5',它只會返回前4次迭代。這在這種情況下可以用於調試。 – 2013-03-14 13:28:27

+0

還要注意,如果你期待*循環(即這是一個圖而不是樹),你必須做一些額外的事情來過濾它們, – 2013-03-14 13:33:35

0

如果你正在使用PostgreSQL的,請嘗試使用WITH clause

WITH regional_sales AS ( 
     SELECT region, SUM(amount) AS total_sales 
     FROM orders 
     GROUP BY region 
     ), top_regions AS (
     SELECT region 
     FROM regional_sales 
     WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales) 
     ) 
SELECT region, 
     product, 
     SUM(quantity) AS product_units, 
     SUM(amount) AS product_sales 
FROM orders 
WHERE region IN (SELECT region FROM top_regions) 
GROUP BY region, product;