2011-08-19 73 views
1

我有以下表結構和數據在MySQLMySQL的 - 在父類總數記錄

 
TABLE NAME : categories 

CatID CatName  ParentCatID 
------------------------------- 
1  Shirts  NULL 
2  Short Sleev 1 
3  Long Sleev  1 
4  Collarless  2 
5  Collar   2 
6  Collarless  3 
7  Collar   3 
8  Square Cut  4 
9  Round Cut  4 
10  Square Cut  6 
11  Round Cut  6 

table name : companies 
------------------------------------------------- 
companyid | company name | country | categoryid 
------------------------------------------------- 
1   | Unitile ltd. | India | 5 
2   | abc ltd.  | India | 2 
3   | infocom ltd. | India | 1 
4   | tata ltd.  | India | 5 
5   | agro india | India | 1 

我有一個2級類別:襯衫>龍黑色PU皮ip

我想在父母的總記錄數類似襯衫

+1

問題在哪裏?你剛剛寫完了這個事實,你想要記錄總數。 –

+0

聽起來像是我需要的分層查詢嗎?看到這個SO問題的指導http://stackoverflow.com/questions/2782525/retrieving-data-with-a-hierarchical-structure-in-mysql –

回答

0

我不明白公司表與該問題有什麼關係。像這樣的事情可能會做你可能試圖做到的事情

SELECT 
C.CatID, COUNT(DISTINCT (IFNULL(PC.CatID, 0))) AS parentcategories 
FROM categories C 
LEFT JOIN categories PC ON (C.ParentCatID = PC.CatID) 
GROUP BY C.CatID 
;