错误统计同一个表的多个连接

时间:2014-02-12 14:02:32

标签: mysql sql join

我有2张桌子

1 - 优惠券

2 - 牵引

对于每个优惠券,在tractions表中可能会有几行 我希望列出所有优惠券和不同条件下的跟踪数量

    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 个答案:

答案 0 :(得分: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

如果您的数据很大,那么您可能需要先将值聚合为子查询,然后再进行连接。