2011-07-01 52 views
2

基本上我有這樣的結構:MySQL的內部聯接造成乘法

  • 交易屬於多個頻道
  • 新政有許多DealSales
  • 新政屬於通道

時,我想找到一筆交易銷售的金額,我用這個查詢:

SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold 
FROM deal_sales 
INNER JOIN deals ON deals.id = deal_sales.deal_id 
INNER JOIN targets ON deals.target_id = targets.id 
WHERE targets.approved = 1 AND targets.active = 1 
GROUP BY targets.id 

它工作得很好,問題是當我需要通過渠道來進行篩選,找到一個交易的渠道銷售金額:

SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold 
FROM 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** 
WHERE targets.approved = 1 AND targets.active = 1 
GROUP BY targets.id 

當我添加了加盟渠道表格中,AMOUNT_SOLD是乘以交易與每個渠道的關係。我怎樣才能避免這種情況?

+0

是規則號1和3正確?,交易 '具有與屬於多個' 或 '屬於' 信道(S)? ?? – fdaines

+0

和目標是什麼?,一筆交易屬於目標? – fdaines

回答

0

或者用已存在

例如

SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold 
FROM deal_sales 
INNER JOIN deals ON deals.id = deal_sales.deal_id 
INNER JOIN targets ON deals.target_id = targets.id 

WHERE targets.approved = 1 AND targets.active = 1 
    and 
    deals.id IN (SELECT deal_id from channels_deals where something = 1) 
GROUP BY targets.id 
+0

謝謝,它工作得很好:D –

0
Try this: 

SELECT channels_deals.deal_id,SUM(deal_sales.amount_sold) AS amount_sold 
FROM 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 
WHERE targets.approved = 1 AND targets.active = 1 
GROUP BY channels_deals.deal_id