Implement Recursive CTE for Hierarchical Query to MariaDB

ⅰ亾dé卋堺 提交于 2019-12-11 06:39:18

问题


I have this table which I would like to store a chain of records.

CREATE TABLE table_name (
    id INT,
    unique_id varchar,
    reference_id varchar,
);

I want to implement SQL query for MariDB which prints all records by unique_id with all record reference_id. Something like this:

| id | unique_id | reference_id |   |   |
|----|-----------|--------------|---|---|
| 43 | 55544     |              |   |   |
| 45 | 45454     | 43           |   |   |
| 66 | 55655     | 45           |   |   |
| 78 | 88877     | 66           |   |   |
| 99 | 454       | 33           |   |   |

I would like when I select record 55544 to get all transactions because each other are using id which points to them. How I can implement this using Recursive CTE? Is there a better way?

Expected result for record with unique_id 55544:

| id | unique_id | reference_id |   |   |
|----|-----------|--------------|---|---|
| 43 | 55544     |              |   |   |
| 45 | 45454     | 43           |   |   |
| 66 | 55655     | 45           |   |   |
| 78 | 88877     | 66           |   |   |

How this query can be implemented also in HQL? I want to use it in JPA?


回答1:


The following query should do what you expect. It's a recursive query that relies on a variable to follow the parent-child relationships trough the dependency tree.

select @ref:=id as id, unique_id, reference_id
from mytable
join (select @ref:=id from mytable WHERE unique_id = 55544)tmp
where reference_id=@ref

This demo on DB Fiddle yields :

| id  | unique_id | reference_id |
| --- | --------- | ------------ |
| 45  | 45454     | 43           |
| 66  | 55655     | 45           |
| 78  | 88877     | 66           |

PS : please note that this does not return the uppermost parent row. If you need it as well, you can change the WHERE condition to :

where reference_id=@ref or unique_id = 55544



回答2:


You can use a recursive CTE. That is the right way to do this:

with recursive cte as (
      select t.*
      from table_name t
      where t.unique_id = 55544
      union all
      select t.*
      from cte join
           table_name t
           on cte.id = t.reference_id
     )
select *
from cte;


来源:https://stackoverflow.com/questions/54393865/implement-recursive-cte-for-hierarchical-query-to-mariadb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!