SQL用于层次关系 [英] SQL for hierarchical relationship

查看:74
本文介绍了SQL用于层次关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,其中的产品是根据树状结构等层次关系进行分类的.我必须选择一个类别以及任何级别的所有子类别.参见下图:

I've a table where products are categorised based on hierarchical relationship like a tree structure. I'm having to select a category and all subcategories at any level. See the picture below:

例如我想要一条sql语句,当我查询传递id = 11时,它返回我(19,20,21,22,23,24,25,26)

e.g. i want an sql statement that when i query passing the id=11, it returns me (19,20,21,22,23,24,25,26)

推荐答案

有几种不同的方法可以在MySQL中存储分层数据.请查看Bill Karwin的演示文稿,其中演示了四个选项.

There are several different ways to store heirarchical data in MySQL. Check out Bill Karwin's presentation that demonstrates four options.

  • 邻接表
  • 路径枚举
  • 嵌套集
  • 关闭表

您正在使用邻接表模型来存储分层数据,但是很遗憾,这是您可以选择的用于查询子树的最困难模型.

You are using the adjacency list model for storing heirarchical data, but unfortunately this is the hardest model you could choose for querying subtrees.

您的选择是:

  • 更改为其他模型.
  • 将查询限制为n级.
  • 使用存储过程进行递归查询.有关此的更多信息,请参阅Quassnoi的系列文章- MySQL中的分层查询.

这篇关于SQL用于层次关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆