将具有自动增量值的两个不同表插入一个表

时间:2018-12-04 01:59:45

标签: java mysql sql select insert

我要从两个不同的表插入一个表:

在我的driver表中,我需要获取driverID作为外键car插入我的driverID_FK表中。

同时,我需要将brand表中的colorwheelmanufacturer插入car表中。

我的桌子:

DRIVER
(driverID, name, age, ...)

CAR
(carID, driverID_FK, brand, color, wheel)

MANUFACTURER
(manufacturerID, brand, color, wheel)

我的driverID是一个自动增量值。而且在我的Web应用程序中,我想插入到car表中的行之前或之后可能还有其他条目,因此不一定是driver表中最后插入的行。 brand, color, wheel表中的manufacturer值也是如此。

到目前为止,这是我准备好的SQL:

String name = //taken from another method...
int manufacturerID = //taken from another method...

String sql = "INSERT INTO car (driverID_FK, brand, color, wheel) 
+ SELECT driverID FROM driver WHERE name = ?,
+ SELECT brand, color, wheel FROM manufacturer WHERE manufacturerID = ? ;";

PreparedStatement psmt = connect.prepareStatement(sql);
psmt.setString(1, name);
psmt.setInt(2, manufacturerID);
psmt.executeUpdate();
psmt.close();

任何建议都将受到赞赏

2 个答案:

答案 0 :(得分:1)

查询1:获取驱动程序ID:

SELECT driverID INTO @driverID
FROM driver
WHERE name = ?

使用先前的@driverID插入制造商信息:

INSERT INTO car (driverID, brand, color, wheel)
SELECT @driverID, brand, color, wheel
FROM manufacturer
WHERE manufacturerID = ?

答案 1 :(得分:0)

使用INSERT .. SELECT语法:

INSERT INTO car (driverID, brand, color, wheel)
SELECT driverID, brand, color, wheel
FROM driver, manufacturer
WHERE name = ? AND  manufacturerID = ?