SQL查询:自引用外键关系
我有两个表,tabSparePart
和 tabSparePartCategory
。每个备件都属于一个备件类别。我需要属于特定类别的所有备件。但问题是,一个备件类别可能是另一个备件类别的“子类别”,它们相互引用(“主类别”在此 FK 列中具有“空”)。
假设我需要 fiSparePartCategory=1
的所有备件以及属于 category=1
的“子类别”类别的所有备件。
如何编写返回所有备件的 SQL 查询,无论有多少级子类别。我希望你能理解我的要求。
以下是我所拥有的说明。如何使其动态化,以便无论子类别有多少,它都可以正常工作?
谢谢,蒂姆
图片链接:http://www.bilder-hochladen.net/files/4709-lg-jpg.html
编辑 :以下是另一种静态方法,该方法在只有一层子类别时有效:
SELECT SparePartName
FROM tabSparePart
WHERE (fiSparePartCategory IN
(SELECT idSparePartCategory
FROM tabSparePartCategory
WHERE (idSparePartCategory = 1) OR
(fiSparePartCategory = 1)))
I have two tables, tabSparePart
and tabSparePartCategory
. Every spare part belongs to a spare part category. I need all spare parts that belong to a specific category. But the problem is that a spare part category could be a "subcategory" of another, they reference each other (the "main categories" have 'null' in this FK column).
Let's say I need all spare parts with fiSparePartCategory=1
and all spare parts that belong to a category that is a "subcategory" of category=1
.
How to write the SQL query that returns all spare parts regardless of how many levels of subcategories there are. I hope you understand my requirement.
The following is an illustration of what I have. How to make it dynamic so that it works regardless of the number of subcategories?
Thanks, Tim
Link to image: http://www.bilder-hochladen.net/files/4709-lg-jpg.html
EDIT: Following is an other static approach which works when there is only one level of subcategory:
SELECT SparePartName
FROM tabSparePart
WHERE (fiSparePartCategory IN
(SELECT idSparePartCategory
FROM tabSparePartCategory
WHERE (idSparePartCategory = 1) OR
(fiSparePartCategory = 1)))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为此,您可以使用递归公用表表达式。
在您的情况下,您需要获取特定主类别 ID 的所有备件类别 ID,并将其与备件连接。像这样的东西:
You can use a recursive Common Table Expression for this.
In your case, you would need to get all sparepart category ids for a specific main category id and join that with the spareparts. Something like this: