MySql Modified preorder tree to create url

强颜欢笑 提交于 2019-12-04 05:00:30

问题


This question is based on my previous question on stackoverflow. This time I am trying to generate urls for all the rows in pages table using the Modified Preorder Tree method.

Here are the MySql Tables: [Note: I have added the 'parent' column just for the viewers to understand the parent-child relationship in the category table. The actual Modified Preorder Tree method does not use parent column (parent-child relationship)]

Category table:

Pages table

I am trying to write a mysql query that will generate URLs for all the rows in the pages table using the category table producing the below output.

Expected rows:

/content/article/array/oops/classes
/content/article/array/oops/objects
/content/article/php/index
/content/article/php/quiz
/content/article/php/strings/strstr
/content/article/php/strings/str_substr
/content/blog/something1
/content/blog/something2
/content/blog/java/test-java
/content/blog/java/final-method
/content/about-us
/content/contact-us

Here is what I tried on category table referring to Managing Hierarchical Data in MySQL. The below SQL query retrieve single path for title 'oops' in category table.

SELECT concat('/',group_concat(parent.title separator '/')) as url
FROM category AS node, category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.title = 'oops'
ORDER BY parent.lft;

回答1:


Something like this should suffice...

SELECT CONCAT_WS('/',x.path,y.page_name) full_path
  FROM
     ( SELECT node.id, GROUP_CONCAT(parent.title ORDER BY parent.lft SEPARATOR '/') path
         FROM category node
         JOIN category parent
           ON node.lft BETWEEN parent.lft AND parent.rgt
        GROUP 
           BY node.title
        ORDER 
           BY node.lft
     ) x
  JOIN pages y
    ON y.category_id = x.id;


来源:https://stackoverflow.com/questions/20422497/mysql-modified-preorder-tree-to-create-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!