mysql - Mysql sum count 来自另一个表的多个列中的出现次数
问题描述
我需要在连接表中找到 id 出现的总和。id 可以出现在两个不同的列中(id_type_1 和 id_type_2)。
表类型
id | name
1 | Test1
2 | Test2
3 | Test3
餐桌产品
id | name | id_type_1 | id_type_2
1 | Product1 | 1 | 2
2 | Product2 | 3 | 1
3 | Product3 | 1 | 3
我需要得到这样的结果:
Type | Total
Test1 | 3
Test2 | 1
Test3 | 2
这是我的查询,但执行需要几秒钟:
SELECT t.name,
(SELECT COUNT(p.id) FROM products p WHERE p.id_type_1 = t.id || p.id_type_2 = t.id) AS total
FROM types t
WHERE 1
ORDER BY total DESC
有没有更有效的方法来达到这个结果?
解决方案
Join the tables and aggregate:
select t.id, t.name,
sum((t.id = p.id_type_1) + (t.id = p.id_type_2)) Total
from types t inner join products p
on t.id in (p.id_type_1, p.id_type_2)
group by t.id, t.name
If there is no case for the id
to exist in both id_type_1
and id_type_2
in the same row then:
select t.id, t.name,
count(*) Total
from types t inner join products p
on t.id in (p.id_type_1, p.id_type_2)
group by t.id, t.name
See the demo.
Results:
> id | name | Total
> -: | :---- | ----:
> 1 | Test1 | 3
> 2 | Test2 | 1
> 3 | Test3 | 2
推荐阅读
- python - 将日期与过去一天进行比较
- javascript - 将 JavaScript 中的数据反向属性添加到动态 HTML 表
- xamarin - 如何在不注销的情况下将 Facebook 登录集成到 Xamarin 表单中
- python - 在 python 程序中从文本文件编译 python 代码显示由于 \n 字符导致的语法错误
- rust - 如何格式化!rust macro_rules 中的 pat(enum)
- django - django 浏览次数显示“NoneType”对象没有属性“comment_set”
- sql - 数据库设计问题:如何参考不同类型的地理区域
- django - 如何在 django 中通过标签发送参数?
- google-apps-script - 我正在 Google 应用脚本上编写电报机器人,数组数据会自动重置,我可以不将用户数据保存到数组中吗?
- python - 生成随机值并根据 pandas 中的条件将它们映射到列