2

我有以下 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

这些值完全搞砸了,返回数千而不是预期的数十和数百。

我理解这个问题,附加表增加了行数。我不确定如何解决这个问题,或者这是否真的是问题所在。

4

2 回答 2

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 
于 2013-03-16T04:41:43.800 回答
0

在 map_polygon 表中,你的 polygon_name 是唯一的吗?那不是唯一的,您可能需要在选择字段中进行更改

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
于 2013-03-16T05:13:13.473 回答