2013-04-26 81 views
-1

我想獲得CategoryID(1);如果它的子類別(2)在內容表中。從子類別選擇頭號類別ID

我的意思是:從contenttable中獲得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 
+0

乾草你能解釋一下它的簡單方式 – 2013-04-26 07:07:47

+0

你的問題不明確。如何將'contenttable'中的'CategoryID'與'categorytable'中的'ParentID'匹配? – iCode 2013-04-26 07:07:54

+0

至少指定你希望你的輸出是怎樣的? – iCode 2013-04-26 07:14:12

回答

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

謝謝,這就是我正在尋找的。但有沒有可能「選擇DISTINCT contenttable.CategoryID'因爲父母重複作爲子數。 – metemet06 2013-04-26 07:49:25

+0

好的,我認爲SELECT'DISTINCT' parent.CategoryID ...解決了問題,再次感謝。 – metemet06 2013-04-26 07:55:15

-1

你的問題,目前尚不得而知。 這個查詢您正在尋找?

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

這些子查詢不是標量子查詢。 – 2013-04-26 07:31:22