するTry 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