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.

    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R