连接表以获取另一列的出现次数

时间:2013-07-08 12:54:09

标签: php mysql sql join

我有两张桌子。一个称为subscriptions,另一个称为service_sushi_service。 我试图获得所有超过2个不同service_id的手机。 例如。

phone: 12345 service id: 12 
phone: 12345 service id: 12 
phone: 12345 service id: 8
phone: 12345 service id: 8
phone: 12345 service id: 13
phone: 22222 service id: 13
phone: 22333 service id: 3

我需要将其输出为phone = 12345,occurences = 3

这是我到目前为止所得到的:我不知道如何更进一步。

SELECT 
    `sub`.`phone` AS `phone`
FROM 
    `subscriptions` AS `sub`
LEFT JOIN `service_sushi_service` `sushi_service` ON `sushi_service`.`sushi_service_id` = `sub`.`sushi_service_id`
WHERE 
    date(`sub`.`added`) >= '2013-01-01'
GROUP BY `sub`.`phone`

3 个答案:

答案 0 :(得分:4)

SELECT 
    `sub`.`phone` AS `phone`,
    COUNT(`sushi_service`.`sushi_service_id`) as occurences        
FROM 
    `subscriptions` AS `sub`
LEFT JOIN `service_sushi_service` `sushi_service` ON `sushi_service`.`sushi_service_id` = `sub`.`sushi_service_id`
WHERE 
    date(`sub`.`added`) >= '2013-01-01'
GROUP BY `sub`.`phone`
HAVING occurences > 2

编辑:应该指出HAVING似乎只是MySQL的一种东西。以为我会发布这个作为参考 - http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html

答案 1 :(得分:3)

我在这段代码中看到了两件事:

  1. 你为什么要做LEFT JOIN?我要说你需要一个直的INNER JOIN

  2. 您可以使用count(distinct field_name)获取相应的值。

  3. 因此SQL看起来像这样:

    SELECT 
        `sub`.`phone` AS `phone`,
         count(distinct `sushi_service`.`sushi_service_id`) as `occurrences`
    FROM 
        `subscriptions` AS `sub`
    JOIN `service_sushi_service` `sushi_service` ON `sushi_service`.`sushi_service_id` = `sub`.`sushi_service_id`
    WHERE 
        date(`sub`.`added`) >= '2013-01-01'
    GROUP BY `sub`.`phone`
    HAVING `occurrences` > 2
    

答案 2 :(得分:1)

根本不需要加入

select s1.phone, count(s1.*) from 
    (select unique phone, sushi_service_id from subscriptions) s1
group by s1.phone having count(s1.*) > 2