我有3个表,T1 T2和T3。
t1_id
,t1_country
t2_id
,t2_country
仅当(t1_id,t2_id)
时,我才需要在T3中插入元组t1_country = t2_country
(t1_id和t2_id是特定的并给出)。
我尝试创建3个查询:
将2个给定的ID插入到第三张表中
pstmt = connection.prepareStatement("SELECT id , country FROM T1"+
" where id= ? ");
pstmt.setInt(1,t1_id);
ResultSet results = pstmt.executeQuery();
pstmt2 = connection.prepareStatement("SELECT * FROM T2"+
" where id= ? AND country=? ");
pstmt2.setInt(1,t2_id);
pstmt2.setString(2,results.getString("country"));
ResultSet results2 = pstmt2.executeQuery();
pstmt3 = connection.prepareStatement("INSERT INTO T3" +
" VALUES (?, ?)");
pstmt3.setInt(1, results.getInt("id"));
pstmt3.setInt(2, results2.getInt("id"));
pstmt3.executeQuery();
答案 0 :(得分:0)
您可以只执行查询
insert into T3
select t1.id, t2.id
from t1
inner join t2 on t1.id = t2.id
and t2.country = t1.country
and t1.id = ?