如何使用查询获取关系子组件?

How to get the relational sub-components using query?

我有一个 table 和 parent-child 在同一个 table。

首先我运行查询SELECT id, pid FROM table_relation where pid = 10。这给出结果

| id  | pid  |
| --- | ---- |
| 92  | 10   |
| 97  | 10   |
| 100 | 10   |

根据结果,我使用 id = 92 进行了查询; 97 & 100 再次使用 id 结果进行另一个查询。

我可以通过使用loop来实现这个结果但是这样我做了太多的循环。有没有办法只使用查询来获得结果?

我尝试使用 UNION,但结果不正确。

SELECT
    e.id,
    e.pid
FROM
    table_relation AS e
WHERE
    e.pid IN (select id from table_relation where pid = 10)
order by e.id ) UNION
(SELECT
    e.id,
    e.pid
FROM
    table_relation AS e
WHERE
    e.id IN (select id from table_relation where pid = 10 order by id)) order by id

MySQL版本8+,有递归通用table表达式

WITH RECURSIVE cte AS (
  SELECT id, pid
  FROM table_relation
  WHERE pid = 10
  UNION
  SELECT table_relation.id, table_relation.pid
  FROM table_relation
  JOIN cte ON cte.id = table_relation.pid
)
SELECT *
FROM cte