mySQL在右表上保持连接(无行)条件

时间:2017-03-08 06:10:37

标签: mysql mysqli

SHOPS
+----+------------+
| id | shop_name  |
+----+------------+

ORDERBOOKINGS
+-----+---------+-------------+------------+
| id  | shop_id | grand_total | created_at |
+-----+---------+-------------+------------+

我想得到一张这样的表:

+------------+--------------+--------------+
| shop_name  | total_orders | total_amount |
+------------+--------------+--------------+

条件是我有日期过滤器,它只返回指定日期之间的订单总数。我想要它返回所有的商店(如果这些日期之间没有一些商店的订单那么它应该返回那些total_orders为0)。

注意:有些商店甚至可能没有订单表中的条目。

我尝试过以下操作,但无法从商店表中返回所有行:

SELECT COUNT(orderbookings.id),
       SUM(orderbookings.grand_total),
       shops.shop_name
FROM `orderbookings`
LEFT JOIN shops
    on orderbookings.shop_id = shops.id
where orderbookings.created_at BETWEEN "2015-10-22 17:02:02" AND "2017-03-07 17:02:02"
GROUP BY shops.id

我知道如何实现这一目标。

感谢。

2 个答案:

答案 0 :(得分:1)

where替换为查询中的and,将LEFT JOIN替换为RIGHT JOIN

SELECT
    COUNT(orderbookings.id),
    COALESCE(SUM(orderbookings.grand_total), 0),
    shops.shop_name 
FROM `orderbookings` 
RIHGT JOIN shops on orderbookings.shop_id = shops.id and orderbookings.created_at BETWEEN "2015-10-22 17:02:02" AND "2017-03-07 17:02:02" 
GROUP BY shops.id

说明:
1)如果你想获得所有的商店,你应该使用shops作为主表,然后离开加入orderbookings,在这里我使用正确的加入,因为你使用orderbookings作为主表; <登记/> 2)如果您使用orderbookings中的where列,则左连接将作为内部联接。

最后,left join解决方案会这样:

SELECT
    COUNT(orderbookings.id),
    COALESCE(SUM(orderbookings.grand_total), 0),
    shops.shop_name 
FROM `shops ` 
LEFT JOIN orderbookings on orderbookings.shop_id = shops.id and orderbookings.created_at BETWEEN "2015-10-22 17:02:02" AND "2017-03-07 17:02:02" 
GROUP BY shops.id

答案 1 :(得分:0)

您想要撤消您的加入并添加一些IFNULL:

SELECT IFNULL(COUNT(orderbookings.id),0),
       IFNULL(SUM(orderbookings.grand_total),0),
       shops.shop_name
FROM `orderbookings`
RIGHT OUTER JOIN shops
    on orderbookings.shop_id = shops.id
       and orderbookings.created_at BETWEEN "2015-10-22 17:02:02" AND "2017-03-07 17:02:02"
GROUP BY shops.id