递归CTE用于对MariaDB进行分层查询

问题描述 投票:1回答:2

我有此表,我想存储记录链。

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

我想为MariDB实现SQL查询,该查询将按unique_id和所有记录reference_id打印所有记录。像这样的东西:

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

我希望选择记录55544来获取所有交易,因为彼此都使用指向它们的id。如何使用递归CTE来实现?有更好的方法吗?

具有唯一ID 55544的记录的预期结果:

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

如何在HQL中也可以实现此查询?我想在JPA中使用它吗?

sql jpa mariadb jpa-2.0 recursive-query
2个回答
1
投票

以下查询应能达到您的期望。这是一个递归查询,它依赖于变量来通过依赖关系树遵循父子关系。

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

demo on DB Fiddle产生:

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

PS:请注意,这不会返回最上面的父行。如果还需要,可以将WHERE条件更改为:

where reference_id=@ref or unique_id = 55544

4
投票

您可以使用递归CTE。这是正确的方法:

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;
© www.soinside.com 2019 - 2024. All rights reserved.