簡體   English   中英

mySQL左連接,右表具有(無行)條件

[英]mySQL left join with (no rows) condition on right table

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

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

我想要一張這樣的桌子:

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

條件是我有日期過濾器,該過濾器僅返回指定日期之間的訂單總數。 我希望它返回所有商店(如果在這些日期之間沒有某些商店的訂單,那么它應該返回那些total_orders為0的商店)。

注意:有些商店甚至可能在訂單表中沒有條目。

我已經嘗試了以下操作,但是它無法從shops表返回所有行:

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

知道我該如何實現嗎?

謝謝。

更換whereand您的查詢和LEFT JOINRIGHT 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)如果您在where使用orderbookings的列,則左聯接將作為內部聯接。

最后, 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

您想撤消聯接並添加一些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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM