开发者

mysql - total count records in parent category

I have following table structure and data in MySQL

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

I have 2 level of categories like : Shirts > Long Sleev

I want total rec开发者_JAVA技巧ords count under parent category like Shirts


I don't understand what the companies table has to do with the problem. Something like this may do what you may be trying to achieive

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
;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜