我有以下数据库结构:
car
+----------+------------+----------------+-----------------+
| car_id | car_name | car_model_id | car_factory_id |
+----------+------------+----------------+-----------------+
car_model
+---------------+----------------+
| car_model_id | car_model_name |
+---------------+----------------+
factory
+-------------+---------------+-------------------+
| factory_id | factory_name | factory_location |
+-------------+---------------+-------------------+
factory_location
+----------------------+------------------------+
| factory_location_id | factory_location_name |
+----------------------+------------------------+
我想:
- 列出所有工厂
- 计算每个工厂生产的汽车数量
- 按 car_model 分组
输出应该是这样的:
| factory_id | car_model_id = 1 | car_model_id = 2 | car_model_id = ... |
+------------+------------------+------------------+--------------------+
| 1 | 145 | 3307 | ... |
+------------+------------------+------------------+--------------------+
| 2 | 32798 | 345 | ... |
+------------+------------------+------------------+--------------------+
| 3 | 0 | 10 | ... |
+------------+------------------+------------------+--------------------+
| ... | ... | ... | ... |
+------------+------------------+------------------+--------------------+
我最接近的尝试是这个请求,但这仍然不是我想要的:
SELECT COUNT(car_id) FROM car GROUP BY car_factory_id AND car_model_id
我的 RDBMS 是 MySQL 5.1。
谢谢你的帮助 :)