mysql join:即使我使用left join,我也不会在左表中获得没有通讯者的行

时间:2014-02-12 13:28:04

标签: mysql sql join

我有2张桌子

1 - 优惠券

2 - 牵引

对于每个优惠券,在tractions表中可能会有几行 我希望得到所有优惠券的清单和它的跟踪数量(本例中为无效)

SELECT `coupons`.*, count(tractions_void.id) as void 

FROM `coupons` 
    LEFT JOIN `tractions` AS `tractions_void` 

ON `tractions_void`.`coupon_parent` = `coupons`.`id` 
    AND `tractions_void`.`expired`  = 1

WHERE `coupons`.`parent` =0

问题是即使我使用左连接,在输出中我只获得至少1次牵引的优惠券....基本上我没有在查询结果中获得0跟踪的优惠券

我希望将它们设为0 tractions_void ...我想如果我使用左连接我不会有这个问题?

2 个答案:

答案 0 :(得分:1)

您需要group by子句:

SELECT c.*, count(t.id) as void
FROM coupons c LEFT JOIN 
     tractions t 
     ON t.coupon_parent = c.id AND
        t.expired  = 1
WHERE c.parent = 0
group by c.id;

我还用较短的别名替换了表名,并删除了反引号以使查询更具可读性。

您的原始查询只返回一行,因为它在select子句中没有聚合函数,并且没有group by子句。

答案 1 :(得分:0)

使用此

 SELECT `coupons`.*, count(tractions_void.id) as void 

 FROM `coupons` 
 LEFT JOIN `tractions` AS `tractions_void` 

 ON `tractions_void`.`coupon_parent` = `coupons`.`id` 


WHERE `coupons`.`parent` =0  
AND `tractions_void`.`expired`  = 1
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^----moved this here in where clause