2012-12-18 76 views
0

我有以下的數據庫結構:如何選擇多個表中的值?

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中。

感謝所有幫助:)

+2

這是什麼RDBMS? –

+0

^這個,看看內部連接。 – zimdanen

+0

RDBMS是mySQL 5.1 –

回答

1

試試這個;)

SELECT a.factory_name , c.car_model_name, 
     COUNT(b.car_factory_id) totalCount 
FROM factory a 
     LEFT JOIN car b 
      ON a.factory_id = b.car_factory_id 
     LEFT JOIN car_model c 
      ON b.car_model_id = c.car_model_id 
GROUP BY a.factory_name , c.car_model_name 
ORDER BY factory_name ASC 
+0

似乎按照我的意願工作至。謝謝 ;) –

1

你一般不能由行的值參數列數,慣用的方式,爲您要使用一個SQL數據庫做什麼查詢得到的東西像這樣的:

factory_id | car_model_id | count 
1   | 1   | 145 
1   | 2   | 3307 
... 
4   | 1   | 3245 
4   | 2   | 38 

在這種情況下,你會怎麼做:

SELECT factory_id, car_model_id, COUNT(*) FROM factory 
INNER JOIN car ON factory_id = car_factory_id GROUP BY factory_id, car_model_id 
+0

我會盡快嘗試,謝謝。 –

+0

您的請求會計算爲每個'car_model_id'生產的汽車數量,並且不會關注'factory_id'參數。輸出如下所示:http://pastebin.com/0JitQehE –

+0

似乎在這個小測試用例中對我來說正確工作。 https://gist.github.com/93de4b75d2f5718a08e3 – yiding