MYSQL count 次数值在 3 列中

标签 mysql

我有一个查询,用于获取有关客户的一些数据。该客户可以拥有三个电话号码,并且可以重复。

要计算这些电话重复的次数,合作伙伴创建了子选择:

(select count(*) 
from TABLE_A as k 
where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone) 
and k.id!=a.id) as repetitionsPhone1

这是一个更大的选择,如下所示:

    SELECT a.*,c.*,b.*, 
    (
        select count(*) 
        from TABLE_A as k 
        where (k.phone=a.phone or k.phone2=a.phone or k.phone3=a.phone) 
        and k.id!=a.id
    ) as repetitionsPhone1
    FROM a
    left join c on a.id=c.id
    left join b on a.id=b.id

此查询需要大约 30 秒,查询 50 行,每天应该返回大约 2000 行。

为了优化这个,我使用explain,我发现这个子查询是问题所在,所以我搜索并尝试了这个:

SELECT phn,sum(count) as phoneRepetitions
from (
    select k.phone1 as phn, count(*) as count
    from k
    group by k.phone1 
        UNION
    select k.phone2 as phn,count(*) as count
    from k
    group by k.phone2
        UNION
    select k.phone3 as phn,count(*) as count
    from k
    group by k.phone3
) as aux
    group by phn

这将返回#1062 MYSQL 错误:键“不同键”的重复条目

首先我想解决这个问题。有人知道发生了什么事吗?这个错误在 insert 语句中似乎是逻辑,但在 select 中?

然后,这将有助于改进我必须优化的大选择?我必须对三列执行此操作。

谢谢。

最佳答案

SELECT count(*) from

  (SELECT phones1 FROM k
    union
  SELECT phones2 from k
    union
  SELECT phones3 from k)

AS SumCountPhones

这似乎对我有用。
解决方案按照How do I add two count(*) results together on two different tables?

您可以继续堆叠联合。

关于MYSQL count 次数值在 3 列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44947402/

相关文章:

java - 使用 Java 中的 sql 查询结果将数据加载到组合对象中

php - 将 AS3 与 PHP 通信。发送变量到php页面,但$_POST为空

mysql - 在 Excel 中引用表格的子集(列)

MySQL计算其他两个计算总和(包括按月分组)的百分比

php - 我无法显示 JOIN 查询的结果

mysql - 如何在mysql中创建循环行值

mysql - 给定一个 SQL Server 2008 R2 *.mdf 文件,如何将它导入 MySQL?

mysql - 比较 2 个 MySQL 表中的最新日期

php - 撇号导致已通过 mysqli_real_escape_string & trim 运行的表项的行重复出现错误

mysql - 如果 "function.mysql-connect"出现在我的网站搜索数据中,人们在试图破解什么?