mysql根据子级查顶级,MySQL父级子级一个查询选择

I have a MySQL table with fields as below:

id name parent

1 Fruit 0

2 Meat 0

3 Orange 1

4 Beef 2

where parent field means the upper level id. For example Fruit id is 1, and Orange is one of the fruit so the parent is 1.

However I want to do an efficient MySQL query to fetch all records in the format parent->children->parent->children format. How can I do that?

The result record of the query should look like:

id name parent

1 Fruit 0

3 Orange 1

2 Meat 0

4 Beef 2

解决方案

You need a recursive join which mysql doesn't support. The only thing you can do is determine the maximum level of depth (i your case it 1 since you have p->c) and with this you can determine the number of joins needed :

maximum level of depth = number of self-joins:

SELECT

p.id as parent_id,

p.name as parent_id,

c1.id as child_id,

c1.name as child_name

FROM

my_table p

LEFT JOIN my_table c1

ON c1.parent = p.id

WHERE

p.parent=0

For example if you max level of depth was 3 the you would need 3 self-joins:

SELECT

p.id as parent_id,

p.name as parent_id,

c1.id as child_id_1,

c1.name as child_name_1,

c2.id as child_id_2,

c2.name as child_name_2,

c3.id as child_id_3,

c3.name as child_name_3

FROM

my_table p

LEFT JOIN my_table c1

ON c1.parent = p.id

LEFT JOIN my_table c2

ON c2.parent = c1.id

LEFT JOIN my_table c3

ON c3.parent = c2.id

WHERE

p.parent=0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值