如何在MySQL上进行高级选择

时间:2012-12-14 07:49:49

标签: mysql database select

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

|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是Sub类别,主要类别是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 |

如何仅过滤主要类别?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

QUERY:

<强> SQLFiddleExample

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 |