我有一张类别表。
Ex(从http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/修改)
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | ELECTRONICS | NULL |
| 2 | TELEVISIONS | 1 |
| 3 | TUBE | 2 |
| 4 | LCD | 2 |
| 5 | PLASMA | 2 |
| 6 | PORTABLE ELECTRONICS | 1 |
| 7 | MP3 PLAYERS | 6 |
| 8 | FLASH | 7 |
| 9 | CD PLAYERS | 6 |
| 10 | 2 WAY RADIOS | 6 |
| 11 | MINI | 7 |
| 12 | OFFERS | NULL |
+-------------+----------------------+--------+
没有父项的条目是根节点。我想创建一个显示根节点及其后代的视图。
例如:
+-------------+----------------------------------------------------------+
| category_id | category_total |
+-------------+----------------------------------------------------------+
| 3 | ELECTRONICS > Televisions > Tube |
| 4 | ELECTRONICS > Televisions > LCD |
| 5 | ELECTRONICS > Televisions > Plasma |
| 8 | ELECTRONICS > Portable electronics > MP3 players > Flash |
| 11 | ELECTRONICS > Portable electronics > MP3 players > Mini |
| 9 | ELECTRONICS > Portable electronics > CD Players |
| 10 | ELECTRONICS > Portable electronics > 2 way radios |
| 12 | OFFERS |
+-------------+----------------------------------------------------------+
如果例如类别5,'等离子'应该得到一个子类别,'等离子'不应该作为此列表中的最终类别,但它的后代应该是:
+-------------+----------------------------------------------------------+
| category_id | category_total |
+-------------+----------------------------------------------------------+
| 3 | ELECTRONICS > Televisions > Tube |
| 4 | ELECTRONICS > Televisions > LCD |
| 13 | ELECTRONICS > Televisions > Plasma > Small |
| 14 | ELECTRONICS > Televisions > Plasma > Big |
| 8 | ELECTRONICS > Portable electronics > MP3 players > Flash |
| 11 | ELECTRONICS > Portable electronics > MP3 players > Mini |
| 9 | ELECTRONICS > Portable electronics > CD Players |
| 10 | ELECTRONICS > Portable electronics > 2 way radios |
| 12 | OFFERS |
+-------------+----------------------------------------------------------+
最多有4个级别的类别。
答案 0 :(得分:0)
尝试此查询(sqlFiddle)
CREATE VIEW myView AS
SELECT c.category_id,
IF(p3.name IS NULL,
IF(p2.name IS NULL,IF(p1.name IS NULL,c.name,CONCAT(p1.name,' > ',c.name)),
CONCAT(p2.name,' > ',p1.name,' > ',c.name)),
CONCAT(p3.name,' > ',p2.name,' > ',p1.name,' > ',c.name)
)
as category_total
FROM category c
LEFT JOIN category child ON child.parent = c.category_id
LEFT JOIN category p1 ON p1.category_id = c.parent
LEFT JOIN category p2 ON p2.category_id = p1.parent
LEFT JOIN category p3 ON p3.category_id = p2.parent
WHERE child.category_id is null;