douchui3933 2019-08-01 02:01
浏览 150

使用php对mysql记录进行高级/技术排序

I am having an issue trying to determine how to sort some data from a mysql database. I have a content items table, and the records contain an id (auto increment), a parent_id (so one page can be a child of another), url, and title.

I want to sort the data in sort of a nested list style, where the main non-child page is first level, and those with that pages id as a parent id are listed below it. Is there a special order to use here, or would this need to be sorted by php?

So, as an example:

id   |  parent_id  | title
---------------------------
1       0            Page 1
3       0            Page 3
6       1            Page 6
7       3            Page 7

The list should look as such:

Page 1
    Page 6
    Any others with parent id of 1
Page 3
    Page 7
    Any others with parent id of 3
  • 写回答

2条回答 默认 最新

  • doumaji6215 2019-08-01 02:18
    关注

    Join the table with itself, joining the parent ID with the ID.

    SELECT parent.title AS parent_page, child.title AS child_page
    FROM yourTable AS parent
    JOIN yourTable AS child ON child.parent_id = parent.id
    ORDER BY parent.id
    

    In your PHP loop, print the parent page heading whenever it changes. See How can i list has same id data with while loop in PHP? for the structure of that loop.

    评论

报告相同问题?

悬赏问题

  • ¥15 MapReduce实现倒排索引失败
  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题