【发布时间】:2019-05-08 22:51:28
【问题描述】:
我有 3 张桌子,T1 T2 和 T3。
- T1 有 2 列:
t1_id、t1_country - T2 也有 2 列:
t2_id、t2_country
我需要在 T3 中插入元组 (t1_id,t2_id)(t1_id 和 t2_id 是特定的且已给出)但仅当 t1_country = t2_country 时。
我尝试创建 3 个查询:
- 从 T1 中选择特定的 t1_id
- 从 T2 t2_id AND country==我在上一个查询中找到的国家/地区中选择。 (通过使用 SELECT...WHERE(..AND..))
-
将 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();
【问题讨论】:
-
有什么问题?你收到什么错误?您使用什么编程语言来执行这些查询?
-
您不需要三个查询,一个
INSERT INTO ... SELECT ...就可以了,而且很可能效率更高。
标签: sql