ruby on rails - mysql inner join causing multiplication -
basically have structure:
- deal has , belongs many channels
- deal has many dealsales
- deal belongs channel
when want find amount sold deal, use query:
select targets.id,sum(deal_sales.amount_sold) amount_sold deal_sales inner join deals on deals.id = deal_sales.deal_id inner join targets on deals.target_id = targets.id targets.approved = 1 , targets.active = 1 group targets.id
its working fine, problem when need filter channel, find amount sold deal in channel:
select targets.id,sum(deal_sales.amount_sold) amount_sold deal_sales inner join deals on deals.id = deal_sales.deal_id inner join targets on deals.target_id = targets.id **inner join channels_deals on channels_deals.deal_id = deals.id** targets.approved = 1 , targets.active = 1 group targets.id
when add join channels table, amount_sold multiplied each channel deal has relation with. how can avoid this?
use in or exists
for example
select targets.id,sum(deal_sales.amount_sold) amount_sold deal_sales inner join deals on deals.id = deal_sales.deal_id inner join targets on deals.target_id = targets.id targets.approved = 1 , targets.active = 1 , deals.id in (select deal_id channels_deals = 1) group targets.id
Comments
Post a Comment