MySQL计算性别实例

时间:2013-03-16 04:36:46

标签: mysql sql select join

我有以下MySQL查询。

USE demo;
SELECT 
  loc.name,
  sum(case cr_sex when 'F' then 1 else 0 end) as 'F#', 
  sum(case cr_sex when 'M' then 1 else 0 end) as 'M#'
FROM case_report_main as cr 
JOIN location as loc on cr.cr_name = loc.name
GROUP BY loc.name

这可以按照我想要的方式运行,它会计算每个性别的每次出现次数,并按位置名称对其进行分组。但是,当我尝试将其与另一个表格连接时

USE demo;
SELECT 
  loc.name,
  sum(case cr_sex when 'F' then 1 else 0 end) as 'F#', 
  sum(case cr_sex when 'M' then 1 else 0 end) as 'M#'
FROM case_report_main as cr 
JOIN location as loc on cr.cr_name=loc.name
JOIN map_polygons as mp on mp.polygon_name=loc.name
GROUP BY loc.name

值完全混乱,返回数千而不是预期的数十和数百。

认为我理解了这个问题,附加表增加了行数。我不知道如何解决这个问题,或者这实际上是问题。

2 个答案:

答案 0 :(得分:1)

因为可能有表map_polygons上有多个匹配项的记录导致性别无效,请尝试将第一个查询放在子查询中,

SELECT  mp.*,
        loc.name
        loc.`F#`
        loc.`M#`
FROM
        (
            SELECT  loc.name,
                    sum(case cr_sex when 'F' then 1 else 0 end) as 'F#', 
                    sum(case cr_sex when 'M' then 1 else 0 end) as 'M#'
            FROM case_report_main as cr 
            JOIN location as loc on cr.cr_name = loc.name
            GROUP BY loc.name
        ) loc
        INNER JOIN map_polygons mp on mp.polygon_name=loc.name 
顺便说一句,既然是mysql,可以将布尔结果总结为更短

SELECT  mp.*,
        loc.name
        loc.`F#`
        loc.`M#`
FROM
        (
            SELECT  loc.name,
                    sum(cr_sex = 'F') as 'F#', 
                    sum(cr_sex = 'M') as 'M#'
            FROM case_report_main as cr 
            JOIN location as loc on cr.cr_name = loc.name
            GROUP BY loc.name
        ) loc
        INNER JOIN map_polygons mp on mp.polygon_name=loc.name 

答案 1 :(得分:0)

在map_polygon表中,ur polygon_name是唯一的吗?这不是唯一的,您可能需要在选择字段中使用chnage

SELECT 
  loc.name,
  count(distinct case cr_sex when 'F' then cr.id else null end) as 'F#', 
  count(distinct case cr_sex when 'M' then cr.id else null end) as 'M#'
FROM case_report_main as cr 
JOIN location as loc on cr.cr_name=loc.name
JOIN map_polygons as mp on mp.polygon_name=loc.name
GROUP BY loc.name