通过这个查询,我从类别中获得了slug,但我希望从孩子那里得到第二个slug。
我想要这些slugs: category / sub-category / items
SELECT i.*, c.slug as cat_slug FROM items i
LEFT JOIN cats c ON c.id = i.cat_id ORDER BY i.id;
分类表
+----------------------------------+
| id | parent_id | name | slug |
+----------------------------------+
| 1 | 0 | Test | test |
+----------------------------------+
| 2 | 1 | Cool | cool |
+----------------------------------+
| 3 | 0 | Test5 | test5 |
+----------------------------------+
项目表
+---------------------------------+
| id | cat_id | title | slug |
+---------------------------------+
| 1 | 2 | Welcome | welcome |
+---------------------------------+
| 2 | 3 | Yeah | yeah |
+---------------------------------+
答案 0 :(得分:0)
只要您对数据结构做出一些假设,特别是只有一个图层,以下查询就是实现此功能的一种方法:
SELECT i.*, c.slug, subcat.slug as cat_slug,
concat_ws('/', c.slug, subcat.slug, i.slug) as total_slug
FROM items i
LEFT JOIN cats c ON c.id = i.cat_id
LEFT JOIN cats subcat on c.parent_id = subcat.id
ORDER BY i.id;
这不适用于超过两个级别的类别。