mySQL count occurrences with JOIN(使用 JOIN 计算 mySQL 出现的次数)
问题描述
我的活动系统有一个标签系统,我想创建一个标签云".
我有活动,可以有多个类别".
表结构如下:
**Event_Categories**(商店标签/类别)|身份证 |姓名 |+---++ 1 |运动 |+ 2 |慈善|+ 3 |other_tag |**Events_Categories**(链接表)|event_id |event_category_id |+------------------------------++ 1 |1 |+ 2 |2 |+ 3 |1 |+ 3 |2 |总结:
事件 ID 1 ->运动事件 ID 2 ->慈善机构事件 ID 3 ->体育、慈善我想返回以下内容:
<代码>|标签名称 |发生|+------------+------------+|运动 |2 ||社会 |2 |
other_tag - 没有实际返回,因为它出现了 0 次
谢谢!:)
这会起作用:
SELECT c.name AS tag_name, COUNT(ec.event_id) AS 出现次数FROM Event_Categories cINNER JOIN Events_Categories ec ON c.id = ec.event_category_id按 c.id 分组如果要包含出现次数为 0 的类别,请将 INNER JOIN 更改为 LEFT JOIN
I have a tagging system for my events system I would like to create a 'tag cloud'.
I have Events, which can have multiple 'categories'.
Here's the table structure:
**Event_Categories** (Stores Tags / Categories)
| id | name |
+-----------------+
+ 1 | sport |
+ 2 | charity |
+ 3 | other_tag |
**Events_Categories** (Linking Table)
| event_id | event_category_id |
+-------------------------------+
+ 1 | 1 |
+ 2 | 2 |
+ 3 | 1 |
+ 3 | 2 |
Summary:
Event ID 1 -> Sport
Event ID 2 -> Charity
Event ID 3 -> Sport, Charity
I'd like to return the following:
| tag_name | occurrences |
+-----------+-------------+
| sport | 2 |
| society | 2 |
other_tag - Not actually returned, as it has 0 occurrences
Thanks! :)
this will work:
SELECT c.name AS tag_name, COUNT(ec.event_id) AS occurrences
FROM Event_Categories c
INNER JOIN Events_Categories ec ON c.id = ec.event_category_id
GROUP BY c.id
change the INNER JOIN to LEFT JOIN if you want to include categories with 0 occurances
这篇关于使用 JOIN 计算 mySQL 出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JOIN 计算 mySQL 出现的次数
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
