首页 > 解决方案 > 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

有没有更有效的方法来达到这个结果?

标签: mysqlcount

解决方案


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

推荐阅读