MySQL子查询仍然产生双SUM值

时间:2017-04-20 15:58:12

标签: mysql join sum duplicates subquery

我确定我做错了事,因为我已经找到了所有的例子。 我确实得到了结果,但总数增加了一倍,或大量重复总数。

查询是:

select 

(st.total_cells) as 'Cells Sorted',

from abstract_freeze af
left join abstract_ejaculate_collection aec on af.ejaculate_collection_id = aec.id
left join mo_flo on aec.id = mo_flo.ejaculate_collection_id
left join sample_time st on mo_flo.id = st.mo_flo_id
left join collection_schedule cs on aec.collection_schedule_id = cs.id
left join collection_plan cp on cs.collection_plan_id = cp.id
left join sub_admission sa on cp.sub_admission_id = sa.id
left join master_admission ma on sa.master_admission_id = ma.id
left join animal on ma.animal_id = animal.id
where aec.tenant_id = 8 and date(aec.scheduled) = '2017-04-12' and sa.type = 'Sexed'
group by aec.id;

将有多个具有相同ejaculate_collection_id的abstract_freeze记录,因此我的SUM(st.total_cells)重复基于周期性af.ejaculate_collection_id的数量。

我似乎无法使我的查询或子查询正确,我需要基于分组的total_cells总和。

2 个答案:

答案 0 :(得分:0)

如果每个id有多条记录,那么您可能希望SUMid而不只是总数,您可以尝试这样做:

select aec.id, SUM(st.total_cells) as 'Cells Sorted',
from abstract_freeze af
left join abstract_ejaculate_collection aec on af.ejaculate_collection_id = aec.id
left join mo_flo on aec.id = mo_flo.ejaculate_collection_id
left join sample_time st on mo_flo.id = st.mo_flo_id
left join collection_schedule cs on aec.collection_schedule_id = cs.id
left join collection_plan cp on cs.collection_plan_id = cp.id
left join sub_admission sa on cp.sub_admission_id = sa.id
left join master_admission ma on sa.master_admission_id = ma.id
left join animal on ma.animal_id = animal.id
where aec.tenant_id = 8 and date(aec.scheduled) = '2017-04-12' and sa.type = 'Sexed'
group by aec.id;

答案 1 :(得分:0)

好的,所以实际上必须在加入前总结一下。 结束了这一点,它得到了正确的价值:

LEFT JOIN (SELECT tc.mo_flo_id, SUM(tc.total_cells) AS cells FROM sample_time tc GROUP BY mo_flo_id) tc USING (mo_flo_id)

...然后

tc.cells AS 'Cells Sorted'

获取正确的求和值。

感谢大家的帮助。