嘗試COALESCE:
DB::raw('COALESCE(COUNT(*), 0) as `orders_per_month`')
此功能允許您定義的默認值時,否則它是NULL。
http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce
UPDATE:
我認爲,如果你選擇哪個具有上個月訂單唯一的客戶,那麼你肯定不會得到這些客戶沒有訂單。
你可以實現你需要的東西像什麼:
mysql> select * from cu;
+----+----------+
| id | name |
+----+----------+
| 1 | Google |
| 2 | Yahoo |
| 3 | Mirosoft |
+----+----------+
3 rows in set (0.00 sec)
mysql> select * from so;
+----+-------------+---------------------+-------+
| id | customer_id | created_at | price |
+----+-------------+---------------------+-------+
| 1 | 1 | 2016-08-23 12:12:12 | 2 |
| 2 | 1 | 2016-09-24 12:14:13 | 3 |
| 3 | 2 | 2016-09-25 00:00:00 | 5 |
| 4 | 2 | 2016-09-12 09:00:00 | 3 |
+----+-------------+---------------------+-------+
4 rows in set (0.00 sec)
mysql> select cu.id as customer_id, coalesce(sum(so.price),0) as total, coalesce(count(so.customer_id),0) as orders_per_month from cu left join so on (cu.id = so.customer_id) where so.created_at >= '2016-09-01 00:00:00' or so.created_at is null group by cu.id;
+-------------+-------+------------------+
| customer_id | total | orders_per_month |
+-------------+-------+------------------+
| 1 | 3 | 1 |
| 2 | 8 | 2 |
| 3 | 0 | 0 |
+-------------+-------+------------------+
3 rows in set (0.00 sec)
然而,得到的查詢將不會爲這種或那種方式非常有效,你必須掃描所有客戶,並加入讓那些沒有命令。獲得帶有訂單的客戶列表並單獨訂購可能會更快,並將其與UNION或通過應用程序代碼合併。
mysql> select customer_id, sum(total) as total, sum(orders_per_month) as orders_per_month from (select id as customer_id, 0 as total, 0 as orders_per_month from cu union all select customer_id, sum(so.price) as total, count(so.customer_id) as orders_per_month from so where created_at >= '2016-09-01 00:00:00'group by customer_id) agg group by customer_id;
+-------------+-------+------------------+
| customer_id | total | orders_per_month |
+-------------+-------+------------------+
| 1 | 3 | 1 |
| 2 | 8 | 2 |
| 3 | 0 | 0 |
+-------------+-------+------------------+
3 rows in set (0.00 sec)
與所有可能的值創建某種日曆表。做外部連接。 – jarlh
或者從您的客戶列表中進行選擇,並在您的紙質桌上進行左連接。 – aynber