【问题标题】:selecting 2 specific values from 2 different tables, and insering them to a third table only if a condition从 2 个不同的表中选择 2 个特定值,并且仅在满足条件时将它们插入到第三个表中
【发布时间】:2019-05-08 22:51:28
【问题描述】:

我有 3 张桌子,T1 T2 和 T3。

  • T1 有 2 列:t1_idt1_country
  • T2 也有 2 列:t2_idt2_country

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

我尝试创建 3 个查询:

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

【问题讨论】:

  • 有什么问题?你收到什么错误?您使用什么编程语言来执行这些查询?
  • 您不需要三个查询,一个 INSERT INTO ... SELECT ... 就可以了,而且很可能效率更高。

标签: sql


【解决方案1】:

你可以只用一个查询来做

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多