0

以下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
4

1 回答 1

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在第一个查询中分组的原因。

于 2013-02-07T07:09:44.283 回答