2012-09-05 69 views
0

車輛如何使用MySQL的查詢

+--------------------+--------------+------+-----+---------+ 
| Field    | Type   | Null | Key | Default | 
+--------------------+--------------+------+-----+---------+ 
| id     | int(11)  | NO | Pk | NULL |  
| model    | varchar(35) | NO |  | NULL |    
+--------------------+--------------+------+-----+---------+ 

信息

+--------------------+--------------+------+-----+---------+ 
| Field    | Type   | Null | Key | Default | 
+--------------------+--------------+------+-----+---------+ 
| id     | int(11)  | NO | Pk | NULL |  
| vehicle_id   | varchar(35) | NO | FK | NULL |  
| location   | varchar(35) | NO |  | NULL |  
+--------------------+--------------+------+-----+---------+ 

車橋1

+--------------------+--------------+------+-----+---------+ 
| Field    | Type   | Null | Key | Default | 
+--------------------+--------------+------+-----+---------+ 
| id     | int(11)  | NO | Pk | NULL |  
| vehicle_id   | varchar(35) | NO | FK | NULL |  
| weight    | varchar(35) | NO |  | NULL |  
+--------------------+--------------+------+-----+---------+ 

車橋2

+--------------------+--------------+------+-----+---------+ 
| Field    | Type   | Null | Key | Default | 
+--------------------+--------------+------+-----+---------+ 
| id     | int(11)  | NO | Pk | NULL |  
| vehicle_id   | varchar(35) | NO | FK | NULL |  
| weight    | varchar(35) | NO |  | NULL |  
+--------------------+--------------+------+-----+---------+ 

我鏈接4桌希望創建一個查詢,該查詢將返回具有常見vehicle_id的所有表中的所有字段。 vehicle_id是車輛表中主鍵的3個表格(信息,車軸1,車軸2)中的每一個的參考。有人可以解釋我可能會這樣做嗎?我嘗試使用多個連接,但它沒有工作!非常感謝。

編輯:

我試過的查詢是;

SELECT * 
     FROM Vehicle 
     JOIN info, axle1, axle 2 
     ON vehicle.id = axle1.vehicle_id 
    AND vehicle.id = axle2.vehicle_id AND vehicle.id = info.vehicle_id 
+2

粘貼您在問題主體中嘗試的查詢。 – Napolux

+0

您可以粘貼寫入的代碼,以便我們開始使用代碼嗎? – Niklas

+0

當然,我編輯了原件,包括我原來的聲明 – Jnanathan

回答

2

試試這個:

SELECT * 
FROM Vehicle v 
INNER JOIN Info i ON   v.id = i.vehicle_id 
INNER JOIN Axle1 a1 ON i.vehicle_id = a1.vehicle_id 
INNER JOIN Axle2 a2 ON a1.vehicle_id = a2.vehicle_id 
0

檢查此鏈接:mySQL get information from multiple tables in one query我認爲有可能適應的例子

你只需要爲每個表的標識,以便您可以指定你在談論某個領域時談論哪個表格。然後,確保將所有ID鏈接爲條件,以便省略標識符不匹配的所有組合。那將是:

SELECT * FROM Vehicle v, Info i, Axle1 a1, Axle2 a2 WHERE v.id == a1.vehicle_id AND v.id == a2.vehicle_id AND v.id == i.vehicle_id