给定一个产品 ID,我需要找到该产品所在的最高类别。
有 3 个顶级类别,我们将它们称为 A、B 和 C。
我有一个包含所有类别的 Categories
表。这包括类别 A、B、C 以及所有子类别,例如 foo、bar 等...
我还有一个名为 ProductCategories
的表。此表包含每个产品的引用以及该产品所属的类别。如果产品属于 Bar 类别,Foo 是 B 的子类别,则结构为 B -> Foo -> Bar
相关产品在 ProductCategories
表中有 3 个条目。
这可能会更好地解释它:
Categories
+--------------------------------+
| ID | Name | ParentID |
+----+----------------+----------+
| 1 | B | Null |
+----+----------------+----------+
| 2 | Foo | 1 |
+----+----------------+----------+
| 3 | Bar | 2 |
+----+----------------+----------+
| 4 | A | Null |
+----+----------------+----------+
| 5 | Subcategory | 4 |
+----+----------------+----------+
| 6 | AnotherSubCat | 5 |
+----+----------------+----------+
| 7 | SoManySubCats | 6 |
+----+----------------+----------+
ProductCategories
+-----------+----------------+
| ProductID | ParentCategory |
+-----------+----------------+
| 50 | 2 | // Product 50 would be:
+-----------+----------------+ // B -> Foo -> Bar
| 50 | 1 |
+-----------+----------------+
| 50 | 3 |
+-----------+----------------+
| 89 | 5 | // Product 89 would be:
+-----------+----------------+ // A -> Subcategory -> AnotherSubCat -> SoManySubCats
| 89 | 4 |
+-----------+----------------+
| 89 | 7 |
+-----------+----------------+
| 89 | 6 |
+-----------+----------------+
对于这个数据库结构,我无能为力。
我不知道如何编写查询,我可以在其中提供产品 ID,它会告诉我顶级类别,A、B 或 < strong>C.
希望有人能阐明这一点。
哦,是的,我正在使用 MS Access 2003。
最佳答案
我用散文描述的查询:将产品的类别与类别表连接起来并选择类别,该类别的 ParentID 为 NULL。
SELECT Categories.Name
FROM Categories, ProductCategories
WHERE ProductCategories.ParentCategory = Categories.ID
AND ProductCategories.ProductID = 50
AND Categories.ParentID IS NULL
关于sql - 如何获取父子结构的根 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6611978/