mysql查询获取根父级

编程入门 行业动态 更新时间:2024-10-28 13:21:55
本文介绍了mysql查询获取根父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在表categories中具有以下数据:

I have the following data in table categories:

id parent_id title -----------------|------------------- 1 0 |A 2 1 |B 3 2 |C 4 3 |D 5 4 |E

现在,我要获取类别ID 4的根类别标题(parent_id 0),即标题A的类别ID 1.

Now I want to get the root category title(parent_id 0) for category id 4 and that is category id 1 of title A.

如何在单个mysql查询中获得所需的结果?我假设将使用过程查询,但我不知道该怎么做.

How can I achieve the required result in a single mysql query? I assume procedural query will be used but I dont know how to do it.

推荐答案

尝试此查询

它的工作原理是,在实际查询之前,记录将按照派生表的降序排序,因此父代的ID小于子代的ID.

It works on the assumption that the id of parent are less than child as the records are being sorted in descending as a derived table before actual query.

select @parent:=parent_id as prnt, title, id from (select @parent:=8 ) a join (select * from tbl order by id desc) b where @parent=id

小提琴

| PRNT | TITLE | ID | |------|-------|----| | 7 | q | 8 | | 6 | a | 7 | | 0 | d | 6 |

注意最好的方法是使用存储的过程.

Note Best way is to do it is using a stored proc..

更多推荐

mysql查询获取根父级

本文发布于:2023-10-26 12:45:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530182.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:mysql   根父级

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!