MYSQL计数次数值为3列

时间:2017-07-06 11:17:33

标签: 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

此查询需要50行约30秒,并且每天应返回约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 error: Duplicate entry for key 'distinct key'

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

之后,这将有助于改善我必须优化的大选择?我将不得不为这三列做到这一点。

谢谢。

2 个答案:

答案 0 :(得分:0)

SELECT count(*) from

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

AS SumCountPhones

这似乎对我有用。
根据{{​​3}}

解决方案

你可以继续堆叠工会。

答案 1 :(得分:0)

SELECT 
COUNT(*) AS CountOf FROM
  table1
    INNER JOIN
table2
GROUP BY phone1 , phone2 , phone3
HAVING COUNT(*) > 1