How to insert data from another table?

Viewed 57

How to insert data from another table? The condition: in table_a, if col_a and col_b = col_p then col_a + col_b and the result is adding to col_q in table_b and col_p in table_a to col_p table_.

try{
String sql0 ="SELECT col_p FROM table_a";
PreparedStatement pst0 = conn.prepareStatement(sql0);
   ResultSet rs0 = pst0.executeQuery();
   int colP = rs0.getInt(1);

String sql1 ="SELECT col_a FROM table_a WHERE col_a=" + colP;
String sql2 ="SELECT col_b FROM table_a WHERE col_b=" + colP;
PreparedStatement pst1 = conn.prepareStatement(sql1);
   ResultSet rs1 = pst1.executeQuery();
   int colA = rs1.getInt(1);
PreparedStatement pst2 = conn.prepareStatement(sql2);
   ResultSet rs2 = pst2.executeQuery();
   int colB = rs2.getInt(1);

String sql3 ="INSERT INTO col_q FROM table_b";
PreparedStatement pst3 = conn.prepareStatement(sql3);
   int colQ = colA + colB;
   pst3.setInt(1, colP);
   pst3.setInt(2, colQ);
   pst3.executeUpdate();
}catch (Exception e){
   System.out.println(e);
}

tables :

table_a table_b

0 Answers
Related