Sql 按父 ID 查询 select

Sql query select by parent id

我需要来自 table 的 select 数据,就像这样(只是示例)。

我想要 select 格式的数据,如 Category1,Category2,Category3 没有根 parent_id

id_category name parent_id
1 root 1
2 Graphic card 1
3 Memory 1
4 DDR3 3
5 Corsair 4
6 HyperX 4

结果应该是

category1 category2 category3
GraphicCard null null
Memory DDR3 Corsair
Memory DDR3 HyperX

可以使用自联接实现此行为。 这应该可以解决问题:

select a.name as category1, b.name as category2, c.name as category3 
from yourtable a
left join yourtable b on a.id_category = b.parent_id
left join yourtable c on b.id_category = c.parent_id
where a.id_category in (2,3);