如何:加入多个表并将所需的列插入一个MySQL

时间:2017-02-12 20:18:51

标签: mysql join sql-insert

我有一些表,我正在尝试使用4个连接加入单个表。

表格是:

车辆

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

我有一个新表车辆正常,它会对车辆表进行规范化,并使用其他3个表作为重复值的查找。

到目前为止,我只有加入所有表的语句:

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语句。我知道我可以使用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个错误。为什么不插入值?

1 个答案:

答案 0 :(得分: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;