我需要一个如下所示的要求,任何人都可以请求帮助我,具体取决于parent_id和id
id | category_name | parent_id
1 Electronics 0
2 computer 1
3 ram 2
4 Fashion 0
5 tshirt 4
6 round neck 5
我需要如下要求
category name | sub category | sub sub category |
Electronics NA NA
Electronics computer NA
Electronics computer ram
Fashion NA NA
Fashion tshirt NA
Fashion tshirt round neck
请帮助
答案 0 :(得分:0)
经过几个小时的痛苦和痛苦,我得到了以下疑问。请注意,上面给出的评论链接对我没有任何帮助。
SELECT t.* FROM
(
SELECT COALESCE(c3.category_name, c2.category_name, c1.category_name, 'NA') AS `category name`,
CASE WHEN c3.category_name IS NOT NULL
THEN c2.category_name
ELSE
CASE WHEN c2.category_name IS NOT NULL
THEN c1.category_name
ELSE 'NA'
END
END AS `sub category`,
CASE WHEN c3.category_name IS NOT NULL
THEN c1.category_name
ELSE 'NA'
END AS `sub sub category`
FROM category c1 LEFT JOIN category c2
ON c1.parent_id = c2.id
LEFT JOIN category c3
ON c2.parent_id = c3.id ) t
ORDER BY t.`category name`,
CASE WHEN t.`sub category` = 'NA' THEN NULL ELSE t.`sub category` END,
CASE WHEN t.`sub sub category` = 'NA' THEN NULL ELSE t.`sub sub category` END
请按照以下链接查看正在运行的演示: