MySQL - 我需要嵌套查询吗?

时间:2012-08-06 09:39:17

标签: mysql

我需要编写一个查询,为每个活动显示男性人数和女性人数。

最好采用3列格式,activity_name,male(计算列),female(计算列)。

我想我可能需要使用嵌套查询,但我无法弄清楚如何。或者这可以通过使用GROUP BY来完成吗?

我的表是:

儿童 child_id child_fname 小孩的名字 child_gender 等等

活动 ACTIVITY_ID ACTIVITY_NAME 等等

Child_Activity_Item child_id ACTIVITY_ID

谢谢

2 个答案:

答案 0 :(得分:0)

这就是你要找的东西:

SELECT  MaleList.Activity_Name,
        MaleList.totalMale,
        FemaleList.totalFemale,
FROM
(
    SELECT  a.Activity_ID, 
            a.Activity_Name,
            COUNT(c.child_gender) totalMale
    FROM    Activity a 
                INNER JOIN Child_Activity_Item b
                    on a.activity_id = b.activity_ID
                INNER JOIN Child c
                    on b.child_id =  c.child_id
    WHERE   c.child_gender = 'male'
    Group BY a.Activity_ID
) as MaleList INNER JOIN
(
    SELECT  a.Activity_ID, 
            a.Activity_Name,
            COUNT(c.child_gender) totalFemale
    FROM    Activity a 
                INNER JOIN Child_Activity_Item b
                    on a.activity_id = b.activity_ID
                INNER JOIN Child c
                    on b.child_id =  c.child_id
    WHERE   c.child_gender = 'female'
    Group BY a.Activity_ID
) as FemaleList 
    ON  MaleList.Activity_ID =  FemaleList.Activity_ID

您不能直接获得三列结果,因为只有列保存了性别。

答案 1 :(得分:0)

尝试此查询 -

SELECT
  a.activity_id,
  a.activity_name,
  COUNT(IF(c.child_gender = 'M', c.child_gender, NULL)) male,
  COUNT(IF(c.child_gender = 'F', c.child_gender, NULL)) female
FROM
  Activity a
  JOIN Child_Activity_Item ca
    ON ca.activity_id = a.activity_id
  JOIN Child c
    ON c.child_id = ca.child_id
GROUP BY a.activity_id