mysql查询;选择类别树中的所有项目

时间:2012-03-15 15:26:10

标签: mysql

我有一个包含类别的表,其中一个类别可以有一个parentid(是其他类别的孩子)。当我想过滤父类别ID上的项目时,我希望查询包含所有子类别。

假设我有这种类别结构:

id || title     || parentid
1  || Sports    || 0
2  || Tennis    || 1
3  || Wimbledon || 2

现在我在温布尔登类别中有一篇文章。我想展示类别运动中的所有文章。

SELECT item.* FROM #table_items AS item WHERE item.catid = 1;

以上查询不会返回温网类别中的文章。这可能吗?

2 个答案:

答案 0 :(得分:0)

SELECT item.* FROM #table_items AS item,#categories as catg
WHERE item.parentid = cat.parentid;

答案 1 :(得分:0)

我得到了我正在寻找的解决方案。假设我想显示ID为12的类别中的所有项目:

SELECT item.* FROM #table_items AS item
LEFT JOIN #__foc_shop_categories AS cat1 ON (cat1.id = item.catid)
LEFT JOIN #__foc_shop_categories AS cat2 ON (cat1.parentid = cat2.id)
... (and so on for more depth)

WHERE (cat1.id = 12 OR cat2.id = 12 OR ...)
GROUP BY item.id

它会产生类别和嵌套类别中的所有项目。

相关问题