MySQL-在一个具有连接ID的表中选择多行

时间:2018-07-19 02:51:33

标签: mysql database

我在mySQL中有一个这样的表

id_file    | file_name     | id_parent
1          | a             | null
2          | b             | null
3          | a_new         | 1
4          | a_new_new     | 3
5          | c             | null
6          | b_new         | 2

我想获取与其他行具有“连通性”的每一行。

我的意思是,当我想选择id_file = 4时,我也可以同时获得id_file = 3和id_file = 1 ...(因为id_file 4 具有父级 id_file 3和id_file 3 id_file 1中拥有父母)

所以当我选择id_file = 4时,结果将是这样

id_file    | file_name     | id_parent
1          | a             | null
3          | a_new         | 1
4          | a_new_new     | 3

我的问题是,要获取与其他行具有连通性的多行(如上面的问题)的查询是什么?

1 个答案:

答案 0 :(得分:0)

改编自https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/

SELECT T2.id_file, T2.file_name,T2.id_parent
FROM (
    SELECT
        @r AS _id,
        (SELECT @r := id_parent FROM tablename WHERE id_file= _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := 4, @l := 0) vars,
        tablename m
    WHERE @r <> 0) T1
JOIN tablename T2
ON T1._id = T2.id_file
ORDER BY T1.lvl DESC;