我确信我做错了什么,因为我已经遵循了找到的所有示例。 我确实得到了结果,但总数加倍或大量重复。
查询是:
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 总和。
最佳答案
如果每个 id
有多个记录,那么您可能需要每个 id
SUM
而不仅仅是总数,您可以尝试以下操作:
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;
关于MySQL子查询仍然产生双SUM值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524487/