0

我只有一张表“tbl_test”

下面给出了表格

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 ;

有谁能够帮我 ?

4

2 回答 2

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;
于 2013-03-14T12:32:50.830 回答
0

如果您使用的是 PostgresSQL,请尝试使用WITH 子句

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;
于 2013-03-14T12:43:32.237 回答