MySQL 查询按父级然后子级排序 [英] MySQL query to order by parent then child places

查看:52
本文介绍了MySQL 查询按父级然后子级排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一个页面表,每个页面都可以有一个父页面,如下所示:

I have a table of pages in my database, each page can have a parent as below:

id            parent_id            title
1             0                    Home
2             0                    Sitemap
3             0                    Products
4             3                    Product 1
5             3                    Product 2
6             4                    Product 1 Review Page

如果有多个级别,那么选择由父级然后子级然后子级排序的所有页面的最佳 MySQL 查询是什么,最多三个级别.上面的例子将产生所需的顺序:

What would be the best MySQL query to select all pages ordered by parent then child then child again if there is more than one level, there will be a maximum of three levels. The above example would produce the desired order:

Home
Sitemap
Products
    Product 1
        Product 1 Review Page
    Product 2

推荐答案

我认为你应该在你的表中多放一个字段,称为 level 并在其中存储节点的级别,然后按级别对查询进行排序,然后按父母.

I think you should put one more field in your table, called level and store in it the level of the node, and then sort your query by level then by parent.

这篇关于MySQL 查询按父级然后子级排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆