2014-02-12 54 views
0

我有2個表的多個錯誤計數與同桌

1加入讓所有的優惠券名單和不同條件下的牽引力的計算

SELECT `coupons`.`id` , 
      count(tractions_all.id) AS `all` , 
      count(tractions_void.id) AS void, 
      count(tractions_returny.id) AS returny, 
      count(tractions_burned.id) AS burned 
     FROM `coupons` 
       LEFT JOIN `tractions` AS `tractions_all` 
         ON `coupons`.`id` = `tractions_all`.`coupon_parent` 
       LEFT JOIN `tractions` AS `tractions_void` 
         ON `coupons`.`id` = `tractions_void`.`coupon_parent` 
         AND `tractions_void`.`expired` =1 
       LEFT JOIN `tractions` `tractions_returny` 
         ON `tractions_returny`.`coupon_parent` = `coupons`.`id` 
         AND `tractions_returny`.`expired` =11 
       LEFT JOIN `tractions` `tractions_burned` 
         ON `tractions_burned`.`coupon_parent` = `coupons`.`id` 
         AND `tractions_burned`.`expired` =0 
         AND '2014-02-12' 
    WHERE `coupons`.`parent` =0 
    GROUP BY `coupons`.`id` 

,現在只有我的優惠券中的一個具有2牽引上都是burned traction其他優惠券已經在所有

這裏沒有牽引力的結果

enter image description here

,你可以看到優惠券與id=13有4個牽引,而應該是2 ...我是什麼我做錯了?如果我刪除最後一次加入,它工作正常,我得到2

回答

1

您正在一次聚合多個維度,導致每個id的笛卡爾產品。

如果你的數據量不是很大,解決這一問題最簡單的方法是使用distinct

SELECT `coupons`.`id` , 
     count(distinct tractions_all.id) AS `all` , 
     count(distinct tractions_void.id) AS void, 
     count(distinct tractions_returny.id) AS returny, 
     count(distinct tractions_burned.id) AS burned 

如果你的數據量大,那麼你可能需要彙總值作爲子查詢,然後再辦連接。