mysql无限极条件查询_关于使用sql语句实现无限极分类查询的疑问

如果只有这三级的话,可以这样自己和自己连表取

语句为:

select a.id as pid, a.name as pname, a.pid as ppid, b.name as ppname

from family a join family b on a.pid=b.id where a.id=儿子的信息的pid;

实例:

db83-3306>>select * from family;

+----+--------+------+

| id | name | pid |

+----+--------+------+

| 1 | 爷爷 | 0 |

| 2 | 父亲 | 1 |

| 3 | 儿子 | 2 |

| 4 | 女儿 | 2 |

+----+--------+------+

db83-3306>>select a.id as pid, a.name as pname, a.pid as ppid, b.name as ppname

-> from family a join family b on a.pid=b.id where a.id=2;

+-----+--------+------+--------+

| pid | pname | ppid | ppname |

+-----+--------+------+--------+

| 2 | 父亲 | 1 | 爷爷 |

+-----+--------+------+--------+

如果级数不知道,可以用类似下面这个语句查询, @r := 2为查询条件

SELECT T2.id, T2.name, T2.pid

FROM (

SELECT

@r AS _id,

(SELECT @r := pid FROM family WHERE id = _id) AS pid,

@l := @l + 1 AS l

FROM

(SELECT @r := 2, @l := 0) vars,

family h

WHERE @r != 0) T1

JOIN family T2

ON T1._id = T2.id

ORDER BY T1.l;

效果

db83-3306>>SELECT T2.id, T2.name, T2.pid

-> FROM (

-> SELECT

-> @r AS _id,

-> (SELECT @r := pid FROM family WHERE id = _id) AS pid,

-> @l := @l + 1 AS l

-> FROM

-> (SELECT @r := 2, @l := 0) vars,

-> family h

-> WHERE @r != 0) T1

-> JOIN family T2

-> ON T1._id = T2.id

-> ORDER BY T1.l;

+----+--------+------+

| id | name | pid |

+----+--------+------+

| 2 | 父亲 | 1 |

| 1 | 爷爷 | 0 |

+----+--------+------+

2 rows in set (0.00 sec)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值