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

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -