我正在尝试使用下表创建SEO友好URL:
我正在尝试编写一个mysql查询,它将使用产生以下输出的类别表为页面表中的所有页面生成URL。
预期输出:
以下是我尝试生成最多4个段的URL的MySql查询:
SELECT pg.id AS page_id, p3.id, p1.category AS segment1, p2.category AS segment2, p3.category AS segment3,
pg.page_name AS PAGE , concat( '/', p1.category, '/', p2.category, '/', p3.category, '/', pg.page_name, '/' ) AS url
FROM category AS p1, category AS p2, category AS p3, pages AS pg
WHERE pg.category_id = p3.id
AND p3.parent_id = p2.id
AND p2.parent_id = p1.id
链接到 SQL Fiddle
答案 0 :(得分:1)
以下是我自己的问题的答案:
我尝试使用“MySql Modified preorder tree to create url”方法,我发现在查询优化和其他通过stackoverflow进行研究方面更有用。
答案 1 :(得分:0)
不是最佳解决方案,但works;)
SELECT pagetable.id AS page_id
, c1.id
, pagetable.page_name AS PAGE
, concat(
IF(c3.category IS NULL,'','/')
, IF(c3.category IS NULL,'',c3.category)
, IF(c2.category IS NULL,'','/')
, IF(c2.category IS NULL,'',c2.category)
, IF(c1.category IS NULL,'','/')
, IF(c1.category IS NULL,'',c1.category)
, '/'
, pagetable.page_name
, '/' ) AS url
FROM pages AS pagetable
LEFT JOIN category AS c1
ON pagetable.category_id = c1.id
LEFT JOIN category AS c2
ON c1.parent_id = c2.id
LEFT JOIN category AS c3
ON c2.parent_id = c3.id