我有一个棘手的问题,希望有人能帮助我。
我有一个类别结构,包括:
示例:
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
提前感谢您的指导。
发布于 2019-07-05 06:40:33
我已经更正了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.pathSQL Fiddle
我没有足够的声誉来添加评论,所以我推出了一个新的answer.Sorry。
发布于 2019-07-04 20:29:41
父id可以为空。请重复检查语法:
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.pathhttps://stackoverflow.com/questions/56893356
复制相似问题