使用mysql的COUNT防止重复

时间:2014-09-02 12:59:21

标签: mysql join count

我有两个表,一个带有国家/地区前缀,另一个带有调用。

前缀表可能如下所示:

+------+-----------+-----------+
|   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呼吁西班牙。

2 个答案:

答案 0 :(得分:1)

我不明白你的电话表的最后一行。根据您的预期结果,我认为它是1而不是1441.尝试使用:

select country, n_calls from
(select destination, count(*) as n_calls from calls group by destination ) as a 
left join 
(select group_concat(country) as country, max(prefix) as destination from country group by prefix) as b
on a.destination=b.destination;

这给了我:

 **country**   **n_calls**
  usa,canada      3
  spain           1

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

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