0

我有表格类别,格式是这样的

|id|parent_id|name|  
|1 |0        |sport|  
|2 |0        |music|
|3 |1        |Stadium|
|4 |1        |Golf| 
|5 |2        |Theater|
|6 |2        |Cinema|

描述

parent_id = 0是主要类别

parent_id != 0是子类别,主类别是 Parent_id

这是表用户

|id|name|category_id|
|1 |andrea|6        |
|2 |Michael | 5     |
|3 |Gorchuf | 1     |

问题

选择包含在用户表上的类别并仅显示主要类别示例目标将是这样的

|id|name|total|
|1 |sport |1  |
|2 |music |2  |

我正在尝试使用此查询

SELECT C.id C.name, count( U.category_id ) AS total
FROM categories C
LEFT JOIN users U ON ( U.category_id = C.id )
GROUP BY C.id
LIMIT 0 , 30

但结果是包括子类别和主要类别

|id|name|total|
|1 |cinema |1 |
|2 |theater|1 |
|3 |sport  |1 |

我怎样才能过滤那个唯一的主要类别?

4

2 回答 2

1

这将解决您的问题-

SELECT pc . * , (SELECT count( * ) FROM category  AS pc1 WHERE pc.id = pc1.parent_id) AS CNT
FROM `category` AS pc
WHERE `parent_id` =0
于 2012-12-14T09:26:59.053 回答
1

询问:

SQLFiddle示例

SELECT c.id, c.name,
(SELECT  count(u.id)
 FROM users u
  LEFT JOIN categories c1
    ON u.category_id = c1.id
  WHERE CASE WHEN c1.parent_id = 0 
             THEN c1.id
             ELSE c1.parent_id 
        END = c.id) AS total
FROM categories c
WHERE c.parent_id = 0
GROUP BY c.id

结果:

| ID |  NAME | TOTAL |
----------------------
|  1 | sport |     1 |
|  2 | music |     2 |
于 2012-12-14T18:15:46.080 回答