从2个不同的表中选择2个特定值,然后仅在有条件的情况下将它们插入到第三个表中

时间:2019-05-08 14:36:27

标签: sql

我有3个表,T1 T2和T3。

  • T1有2列:t1_idt1_country
  • T2还具有2列:t2_idt2_country

仅当(t1_id,t2_id)时,我才需要在T3中插入元组t1_country = t2_country(t1_id和t2_id是特定的并给出)。

我尝试创建3个查询:

  1. 从T1中选择特定的t1_id
  2. 从T2 t2_id中选择AND国家==我在上一个查询中找到的国家。 (通过使用SELECT ... WHERE(.. AND ..))
  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();
    

1 个答案:

答案 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  = ?