2017-04-20 205 views
0

我確定我做錯了什麼,因爲我已經遵循了所有發現的例子。 我確實得到了結果,但總數翻倍或大量複製總數。MySQL的子查詢仍然會產生兩倍的SUM值

查詢是:

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; 

將有多個abstract_freeze記錄與同ejaculate_collection_id,爲此我SUM基於重複af.ejaculate_collection_id的數量(st.total_cells)重複。

我可以似乎得到我的查詢或子查詢正確的,我需要基於分組total_cells的總和。

+0

我沒有看到任何地方發生的金額。這是你的整個查詢嗎? –

+0

對不起,我刪除了一些行來縮短它,因爲我專注於「單元排序」,但它應該讀取SUM(st.total_cells)。我的錯。 –

回答

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; 
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' 

得到適當的彙總值。

感謝大家的幫助。