将多行数据透视到单列
我有一个数据库表,其中包含不同产品的类别。每个类别只有一个父类别,每个产品可以有多个类别。我需要为数据迁移构建一种面包屑导航,但无法弄清楚如何映射数据,这样我就不会进行大量查询。
数据库的设置如下:
id category sort parent
1 Home 0 0
58 Car & Truck 4 1
135 10' Wide Shelters 0 58
现在我需要像这样取回数据: Home/Car &卡车/10'宽避难所
。
这可以用纯 SQL 实现吗?还是需要混合 ColdFusion 才能实现?如果我可以用纯 SQL 做到这一点,那么我将如何做到这一点,如果我不能,那么 ColdFusion 会是什么样子?
I have a database table with categories for different products in it. Each category has only one parent and each product can have multiple categories. I need to build a sort of breadcrumb navigation for a data migration, but can't figure out how to map the data so that I don't have tonds of queries.
The database is setup like so:
id category sort parent
1 Home 0 0
58 Car & Truck 4 1
135 10' Wide Shelters 0 58
Now I need to get the data back like this: Home/Car & Truck/10' Wide Shelters
.
Is this possible with pure SQL or do I need to mix-in ColdFusion to get it. If I can do this with pure SQL then how would I do that, and if I can't then what would the ColdFusion look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其他 RDBMS 支持解决此问题的各种方法(ANSI SQL 中的递归
with
、Oracle 中的connect by
等)。但在 MySQL 中,你几乎只剩下嵌套集。Other RDBMSes support various ways of solving this problem (recursive
with
in ANSI SQL,connect by
in Oracle, etc). But in MySQL, you're pretty much left with nested sets.使用嵌套集,按照 user349433 的建议,我能够提出这个查询“
我的数据永远不会超过 5 层”(我通过检查 c6 并获取空值进行验证)。从这里我可以对此进行查询,
我已经查询了产品及其类别 id 来循环。
Using nested sets, as recommended by user349433 I was able to come up with this query
My data never goes deeper than 5 levels (I verified by checking with c6 and getting nulls). From here I can query against this
I already had a query of products and their category ids to loop over.