gpt4 book ai didi

mysql - 如何在 MySQL 上进行高级选择

转载 作者:行者123 更新时间:2023-11-29 08:40:41 26 4
gpt4 key购买 nike

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

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

如何过滤该主要类别?

最佳答案

查询:

<强> 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 |

关于mysql - 如何在 MySQL 上进行高级选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13874636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com