我要从两个不同的表插入一个表:
在我的driver
表中,我需要获取driverID
作为外键car
插入我的driverID_FK
表中。
同时,我需要将brand
表中的color
,wheel
和manufacturer
插入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();
任何建议都将受到赞赏
答案 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 = ?