我有一个棘手的问题,希望有人可以帮助我。
我的类别结构包括:
示例:
1 Root/Arts Arts
2 Root/Arts/Animation Animation
3 Root/Arts/Animation/Anime Anime
4 Root/Arts/Animation/Anime/Characters Characters
5 Root/Arts/Animation/Anime/Clubs_and_Organizations Clubs_and_Organizations
6 Root/Arts/Animation/Anime/Collectibles Collectibles
7 Root/Arts/Animation/Anime/Collectibles/Cels Cels
8 Root/Arts/Animation/Anime/Collectibles/Models_and_Figures Models_and_Figures
9 Root/Arts/Animation/Anime/Collectibles/Models_and_Figures/Action_Figures Action_Figures
10 Root/Arts/Animation/Anime/Collectibles/Models_and_Figures/Action_Figures/Gundam Gundam
11 Root/Arts/Animation/Anime/Collectibles/Models_and_Figures/Action_Figures/Zoids Zoids
12 Root/Arts/Animation/Anime/Collectibles/Models_and_Figures/Models Models
13 Root/Arts/Animation/Anime/Collectibles/Models_and_Figures/Models/Gundam Gundam
14 Root/Arts/Animation/Anime/Collectibles/Shitajiki Shitajiki
我需要为每一行标识父类别,以便表看起来像这样:
数据在SQL中,但是我也有文本文件,可以在命令行上完成此操作。也许它是工作的更好工具?
这是一个SQL提琴,使用下面提供的查询和上面的示例数据:
http://sqlfiddle.com/#!9/e060ec/1
在此先感谢您的指导。
答案 0 :(得分:1)
我的sql正确。
SELECT c.id, c.name, c.path, p.id AS parent_id
FROM cat_test p
RIGHT JOIN (
SELECT id, name,path, LEFT(path,LENGTH(path) - LENGTH(name)-1) AS parent
FROM cat_test) c
ON c.parent=p.path
我没有足够的声誉来添加评论,所以我提出了一个新答案。很抱歉。
答案 1 :(得分:0)
父ID可以为null。请仔细检查语法:
SELECT c.id, c.name, c.path, p.id AS parent_id
FROM category_table p
RIGHT JOIN (
SELECT id, name,path, LEFT(path,LENGTH(path) - LENGTH(name)+1) AS parent
FROM category_table) c
ON c.parent=p.path