代码之家  ›  专栏  ›  技术社区  ›  JOSI

从两个不同的表中选择2个特定值,并且仅当条件

sql
  •  0
  • JOSI  · 技术社区  · 5 年前

    我有三张桌子,T1、T2和T3。

    • T1有两列: t1_id , t1_country
    • t2也有2列: t2_id , t2_country

    我需要把这个元组插入到t3中 (t1_id,t2_id) (T1_id和T2_id是特定的和给定的),但前提是 t1_country = t2_country .

    我尝试创建3个查询:

    1. 从T1中选择特定的T1-ID
    2. 从t2 t2_id和country==我在上一个查询中找到的国家。(通过使用select…其中(..和..)
    3. 将2个给定ID插入第3个表

          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 回复  |  直到 5 年前
        1
  •  0
  •   ScaisEdge    5 年前

    你只需要一个查询就可以了

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