我有一张 table
+-------------+--------------------+----------------------+-----------------------------+
| category_id | parent_category_id | category_path | category_name |
+-------------+--------------------+----------------------+-----------------------------+
| 13098 | 0 | 0 | Scooter 100cc+ |
| 13099 | 13098 | 0,13098, | Aprilia |
| 13100 | 13099 | 0,13098,13099, | Atlantic/Arrecife 125 LC 4T |
| 13101 | 13100 | 0,13098,13099,13100, | Fahrwerk |
+-------------+--------------------+----------------------+-----------------------------+
MySQL 中有没有办法构建 category_path
作为 category_path
字段的替换?
因此,在 category_path
字段的最后一行有
|Scooter 100cc, Aprilia, Atlantic/Arecife 125 LC 4T|
而不是
|0,13098,13099,13100|
最佳答案
您确实应该考虑优化数据库并将其规范化,因为将数据存储为逗号分隔数据会导致您将来遇到许多问题。
最好创建一个关联表并将每个类别的一对多记录存储到该表中。
但是在当前情况下,您可以使用find_in_set()
作为
select
c1.category_id,
c1.parent_category_id,
group_concat(c2.category_name) as category_path,
c1.category_name
from category c1
left join category c2 on find_in_set(t2.parent_category_id,c1.category_path)
group by c1.category_id;
关于mysql操作结果,替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29645682/