gpt4 book ai didi

mysql - 使用 mysql 的 COUNT 防止重复

转载 作者:行者123 更新时间:2023-11-29 07:54:02 25 4
gpt4 key购买 nike

我有两张表,一张带有国家/地区前缀,另一张带有调用的电话。

前缀表可能如下所示:

+------+-----------+-----------+
| id | country | prefix |
+------+-----------+-----------+
| 1 | USA | 1 |
| 2 | canada | 1 |
| 3 | spain | 4 |
+------+-----------+-----------+

调用表:

+-----------+-------------------+
| id | destination |
+-----------+-------------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 4 |
| 4 | 1441 |
+-----------+-------------------+

我正在尝试查找打往每个国家/地区的电话数量:

select count(*) as calls
from calls as t1
inner join prefixes as t2
on t1.destination like CONCAT('%', t2.prefix)

问题是美国和加拿大具有相同的前缀,我得到双重结果,我还必须使用当前表格而不添加/编辑。

是否可以迭代调用表,但只搜索每个前缀一次?

预期结果:3 个调用前缀 1(美国/加拿大),1 次调用西类牙。

最佳答案

使用您的确切数据的另一种方法是:

select count(*) as calls, t2.country as country
from calls as t1
left join
(select group_concat(country) as country, prefix from prefixes group by prefix) as t2
on t1.destination like CONCAT(t2.prefix, '%')
group by substring(t1.destination,1,1)

结果是:

| CALLS |    COUNTRY |
|-------|------------|
| 3 | USA,Canada |
| 1 | Spain |

这里有相应的SQLFiddle

这种方法应该更快,因为嵌套查询更少。

关于mysql - 使用 mysql 的 COUNT 防止重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25624045/

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