简体   繁体   English

同一张表的多个联接计数错误

[英]wrong count on the multiple joins with the same table

i have 2 tables 我有2张桌子

1 - coupons 1-优惠券

2 - tractions 2-牵引力

for each coupon there might be couple of rows in tractions table I want to have list of all coupons and count of its tractions under different condition 对于每个优惠券,牵引力表中可能会有几行,我想拥有所有优惠券的列表以及在不同条件下的牵引力计数

    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`

right now only one of my coupons has 2 traction on both are burned traction other coupons have no tractions at all 现在,我的一张优惠券上只有2牵引力都burned traction其他的优惠券根本没有牵引力

here is the result 这是结果

在此处输入图片说明

as you can see coupon with id=13 has 4 traction while it should be 2 ... what am i doing wrong ? 如您所见, id=13优惠券的牵引力为4,而应该为2 ...我在做什么错? if i remove the last join it works fine and i get 2 如果我删除最后一个连接,它工作正常,我得到2

You are aggregating along multiple dimensions at one time, resulting in a cartesian product for each id. 您一次沿多个维度进行汇总,因此每个ID都会产生笛卡尔积。

If your data volume is not very large, the easiest way to fix this is using distinct : 如果您的数据量不是很大,则解决此问题的最简单方法是使用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

If your data is large, then you will probably need to aggregate values as subqueries first and then do the joins. 如果数据很大,则可能需要先将值聚合为子查询,然后再进行联接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM