MySQL 中的分层查询

2021-11-20 00:00:00 hierarchical-data mysql

我正在尝试以任意深度查找特定领域的所有父母、祖父母等.例如,给定下面的结构,如果我提供 5,返回的值应该是 1、2、3 和 4.

I'm trying to find all the parents, grandparents, etc. of a particular field with any depth. For example, given the below structure, if I provide 5, the values returned should be 1, 2, 3 and 4.

| a  | b  |
-----------
| 1  | 2  |
| 2  | 3  |
| 3  | 4  |
| 4  | 5  |
| 3  | 6  |
| 4  | 7  |

我该怎么做?

推荐答案

SELECT  @id :=
        (
        SELECT  senderid
        FROM    mytable
        WHERE   receiverid = @id
        ) AS person
FROM    (
        SELECT  @id := 5
        ) vars
STRAIGHT_JOIN
        mytable
WHERE   @id IS NOT NULL

相关文章