从子类别ID中选择顶级类别

时间:2013-04-26 07:02:06

标签: mysql sqlite

我想获得CategoryID(1);如果其子类别(2)在内容表中。

我的意思是:从内容表中获取categoryid(2);在类别表中找到它的parentid(1);并选择顶级类别行(categoryid:1) - 所以我无法选择内容的顶级类别行,我该怎么做?

categorytable:

CategoryID , ParentID
    1            0
    2            1

contenttable:

  _id, CategoryID
  ...       2 

代码:

   SELECT DISTINCT contenttable.CategoryID, categorytable.CategoryID FROM categorytable 
                    INNER JOIN contenttable 
                    ON categorytable.CategoryID = contenttable.CategoryID

2 个答案:

答案 0 :(得分:1)

SELECT parent.CategoryID
FROM categorytable AS parent
JOIN categorytable AS child ON child.ParentID = parent.CategoryID
JOIN contenttable           ON child.CategoryID = contenttable.CategoryID

答案 1 :(得分:-1)

您的问题仍不清楚。 这是您要查找的查询吗?

select CategoryID.categorytable from categorytable where CategoryID.categorytable=(select ParentID.categorytable from categorytable where CategoryID.categorytable=(select CategoryID.contenttable from contenttable));