【问题标题】:prevent duplicate with mysql's COUNT防止与 mysql 的 COUNT 重复
【发布时间】:2023-03-18 10:42:01
【问题描述】:

我有两张表,一张带有国家前缀,另一张带有拨打电话。

前缀表可能如下所示:

+------+-----------+-----------+
|   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 次致电西班牙。

【问题讨论】:

  • 通过这些表格,您无法根据定义找出每个国家/地区的通话次数,因为您无法区分美国和加拿大。那么你期望结果是什么? 1.两次美国,一次西班牙; 2.两次加拿大,一次西班牙; 3.美国一次,加拿大一次,西班牙一次; 4. 还有什么?
  • 谢谢,添加了预期结果

标签: mysql join count


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

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

【讨论】:

    【解决方案2】:

    我不明白您调用表的最后一行。根据您的预期结果,我认为它是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 2019-12-04
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多