2017-03-08 61 views
0
SHOPS 
+----+------------+ 
| id | shop_name | 
+----+------------+ 

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

我希望得到像這樣的表:MySQL的左用(沒有行)連接條件上右表

+------------+--------------+--------------+ 
| 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 

任何想法,我怎麼能做到這一點?

謝謝。

回答

1

更換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 
+0

已經嘗試過。仍然只返回在訂單表中有條目的商店。離開所有其他商店。 –

+0

@ nikhil.malik更新了我的答案,請再次檢查。 – Blank

+0

現在工作。感謝名單! –

0

你想扭轉你的加入,並添加一些IFNULLs:

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 
+1

您可能需要將'WHERE'條件移至'ON'子句。 –

+0

沒有幫助。仍然只返回訂單表中有訂單的那些商店。離開所有其他商店。你想讓我提供真實的數據嗎? –

+0

吶喊,加入語法有點生疏。嘗試一個正確的外部連接。更新了答案。 – Ilion