如何从数据库中提取孙子
我想从 MySQL 中提取菜单项。
Main menu id=1, parentid=0
-Contact us id=2, parentid=1
-Music id=3, parentid=1
--Rock id=8, parentid=3
--Classic id=9, parentid=3
-Car id=4, parentid=1
--Toyota id=5, parentid=4,
--Ford id=6, parentid=4,
--Honda id=7, parentid=4
Other menu id=10, parentid=0
-Othermain id=11, parentid=10
--submenu id=12, parentid=11
etc.
我可以从 id=1 到 4 提取数据并通过“...whereparentid=1”等显示。 然而,这仅拉出了顶层。
但我想提取所有数据,包括每个菜单(主菜单)的子菜单。
谁能告诉我如何在 MySQL 中为此编写查询?
提前致谢。
I want to pull out menu items from MySQL.
Main menu id=1, parentid=0
-Contact us id=2, parentid=1
-Music id=3, parentid=1
--Rock id=8, parentid=3
--Classic id=9, parentid=3
-Car id=4, parentid=1
--Toyota id=5, parentid=4,
--Ford id=6, parentid=4,
--Honda id=7, parentid=4
Other menu id=10, parentid=0
-Othermain id=11, parentid=10
--submenu id=12, parentid=11
etc.
I can pullout data from id=1 to 4 and display by "...where parentid=1" etc.
However this pulls out only the top level.
But I want to pullout all the data including submenu for each menu(main menu) as well.
Could anyone tell me how to write a query in MySQL for this please?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要实现递归来重复调用数据库来检索所有子项。您必须用您自己的数据库抽象层实现替换我的数据库抽象层实现,但概念是相同的。
memcache 解决方案
非 memcache 解决方案
以上未经测试,因此如果有人发现错误,请告诉我或随时更新。
You need to implement recursion to make repeated calls to the database to retrieve all children. You will have to replace my database abstraction layer implementation with your own but the concept is the same.
memcache solution
non memcache solution
The above is untested so if anybody catches an error please let me know or feel free to update.
最快的方法是从表中获取所有元素并在代码端构建菜单树。
The fastest way is to fetch all elements from the table and build menu tree in the code side.