複数のテーブルを選択して空のカラムを持つようにしようとしています。例えば 私のテーブル:SQLが複数のテーブルを結合したままになりました
calendar: //filled with dates from 2011-01-01 to 2015-12-31
+-----------+
| datefield |
+-----------+
| 2012-1-1 |
| 2012-1-2 |
| ... |
| 2012-2-3 |
| 2012-2-4 |
+-----------+
car:
+--------+---------+
| car_id | name |
+--------+---------+
| 1 | Ford |
| 2 | Peugeot |
| 3 | Fiat |
+--------+---------+
carsales:
+-------------+-----------+--------+-------------+
| car_sale_id | sell_time | car_id | customer_id |
+-------------+-----------+--------+-------------+
| 1 | 2012-1-2 | 1 | 1 |
| 1 | 2012-1-2 | 2 | 1 |
| 2 | 2012-1-3 | 3 | 2 |
+-------------+-----------+--------+-------------+
customer:
+-------------+---------+
| customer_id | country |
+-------------+---------+
| 1 | NL |
| 2 | EN |
+-------------+---------+
は今、私は車名で「NL」から顧客によって販売されている車の量のリストが欲しい、そして2012年1月1日と2012年2月1日の間(で週間)。日付は常に存在する必要があります。例えば
:
SELECT WEEKOFYEAR(calendar.datefield) as 'Week', car.name, COUNT(carsales.car_id)
FROM car, customer, calendar
LEFT JOIN carsales ON DATE(calendar.datefield) = DATE(carsales.sell_time)
WHERE calendar.datefield > '2012-01-01' AND calendar.datefield < '2012-02-01'
AND car.id = carsales.car_id
AND customer.country = 'NL'
AND customer.customer_id = carsales.customer_id
GROUP BY 'Week', car.name
ORDER BY 'Week', car.name;
は、私が何をしないのです:
+----------+----------+-------+
| Week | Car name | Sales |
+----------+----------+-------+
| 1 | Ford | 0 |
| 1 | Peugeot | 0 |
| 1 | Fiat | 0 |
| 2 | Ford | 1 |
| 2 | Peugeot | 1 |
| 2 | Fiat | 0 |
| 3 | Ford | 0 |
| 3 | Peugeot | 0 |
| 3 | Fiat | 0 |
| etc | ... | ... |
+----------+----------+-------+
私はこの思い付きましたか?
カレンダーテーブルのポイントは何ですか? –
'carsales.customer_id = customer.id'のような条件がありません。暗黙的な結合と明示的な結合を組み合わせることもあります。テーブルを結合するには 'JOIN'キーワードを使います。 –
@ypercube、それは答えでなければならない –