mysql查询来获取个别ID的计数

时间:2013-02-07 07:07:30

标签: mysql sql group-by

以下mysql查询将给出如下结果

$query = "SELECT PS.user_id, PS.pro_id
    FROM pro_Purchase AS PS
    INNER JOIN program_detail AS PD ON PD.program_master_id = PS.pro_id
    WHERE PD.program_type = 'program'
    AND PS.subscribe_status = '1'
    GROUP BY PS.`programs_subscribed_id`
    HAVING COUNT( `pro_id` ) > '1'
    ORDER BY PS.pro_id"

结果

user_id program_id
97      167     
12      172     
12      172     
216     173     
216     173     
215     173     
216     173     
12      173     
12      173     
12      173     
216     173     

我希望获得每个count

program_id

例如:count(172),count(173)等等。

id   count
172  2

1 个答案:

答案 0 :(得分:0)

您可以将查询包装在子查询中并按如下方式计入外部查询:

SELECT 
  user_id, COUNT(pro_id)
FROM
(
    SELECT PS.user_id, PS.pro_id
    FROM pro_Purchase AS PS
    INNER JOIN program_detail AS PD ON PD.program_master_id = PS.pro_id
    WHERE PD.program_type = 'program'
      AND PS.subscribe_status = '1'
    GROUP BY PS.programs_subscribed_id
    HAVING COUNT( pro_id ) > '1'
) AS Sub
GROUP BY user_id
ORDER BY pro_id;

请注意:您发布的查询中的是按PS.programs_subscribed_id进行分组,并在PS.user_id, PS.pro_id子句中选择SELECT既不是聚合函数也不是在GROUP BY子句中,所以你不会以这种方式获得不一致的数据。

您可以这样做:

SELECT PS.pro_id, COUNT(PS.user_id)
FROM pro_Purchase AS PS
INNER JOIN
(
   SELECT programs_subscribed_id
   FROM pro_Purchase 
   GROUP BY programs_subscribed_id
   HAVING COUNT( pro_id ) > 1
) AS PS2 ON PS.programs_subscribed_id = PS2.programs_subscribed_id
INNER JOIN program_detail AS PD ON PD.program_master_id = PS.pro_id
WHERE PD.program_type = 'program'
  AND PS.subscribe_status = '1'
GROUP BY PS.pro_id;

这样,带有子查询的额外JOIN

   SELECT programs_subscribed_id
   FROM pro_Purchase 
   GROUP BY programs_subscribed_id
   HAVING COUNT( pro_id ) > 1

确保从pro_Purchase表中选择的每一行COUNT( pro_id ) > 1都有programs_subscribed_id,这就是您在第一次查询中按programs_subscribed_id分组的原因。