2017-02-12 69 views
0

我想要使用4個連接將一些表加入到一個表中。如何:加入多個表並將所需列插入到一個MySQL中

的表是:

車輛

vehicleId 
make 
model 
year 
cylinders 
displacement 
drive 
engid 
eng_dscr 
trany 
mpgHighway 
mpgCity 
fuelCostAnnual 
fuelType 
fuelType1 
vClass 

vehicledrive

driveId 
driveName 

vehiclefueltype

fuelId 
fuelName 

vehiclemake

makeId 
makeName 

vehiclemodel

modelId 
modelName 

我有一個新的表,vehiclenormal,其歸一化車輛表,並且使用其他3代表作爲look-重複價值。

到目前爲止,我已經是聯接中的所有表的語句:

select vehicle.*, vehicledrive.*, vehiclefueltype.*, vehiclemake.*, vehiclemodel.* 
from vehicle 

join vehicledrive 
on vehicle.drive = vehicledrive.driveName 

join vehiclefueltype 
on vehicle.fueltype = vehiclefueltype.fuelname 

join vehiclemake 
on vehicle.make = vehiclemake.makename 

join vehiclemodel 
on vehicle.model = vehiclemodel.modelname 

order by vehicle.vehicleid 

我的問題是,我不知道如何添加插入語句。我知道我可以使用insert into ... select,但是如何根據連接的結果指定要插入的列和行?

編輯:好吧,我已經找到了如何只選擇我要插入的數據,我想下面的查詢:

insert into vehiclenormal (makeid, modelid, year, cylinders, driveid, mpghighway, mpgcity, fueltypeid) 
(select makeid, modelid, year, cylinders, driveid, mpghighway, mpgcity, fuelid 
from vehicle 
join vehicledrive on vehicledrive.driveName = vehicle.drive 
join vehiclefueltype on vehiclefueltype.fuelName = vehicle.fueltype 
join vehiclemake on vehiclemake.makeName = vehicle.make 
join vehiclemodel on vehiclemodel.modelname = vehicle.model); 

但HeidiSQL是說有超過21,000的錯誤。爲什麼不插入值?

回答

2

只需使用INSERT INTO語法:

insert into vehiclenormal 
    (makeid, modelid, year, driveName, fuelName, makeName, modelName) 
    select d.makeId, e.modelId, a.year, b.driveName, c.fuelName, d.makeName, e.modelName 
    from vehicle a 
     join vehicledrive b on a.drive = b.driveName 
     join vehiclefueltype c on a.fueltype = c.fuelName 
     join vehiclemake d on a.make = d.makeName 
     join vehiclemodel e on a.model = e.modelName; 
+0

其實我只是試圖插入進去,但我得到了什麼,但警告。我剛剛編輯了我的原始帖子。 –

+0

我沒有在例子中包含車輛中的所有列,但希望你知道無論如何... –

+0

a,b,c,d,e的意義是表名,對嗎?如果是這樣,爲什麼需要這麼明確? –