简体   繁体   中英

Insert and update a table at the same time

I have two tables named 'Trending' and 'Questbank'.

Im trying to insert trending table and update the questbank table at the same time. Following is my code.

PreparedStatement stmt = connection.prepareStatement(
                    "INSERT INTO TRENDING ( TOPIC , CATEGORY , QUESTION , ANSWER , PROFILEPIC , TICK , URL ) VALUES( ?, ? , ? , ? , ? , now() , ? )  Returning ID AND UPDATE  QUESTBANK SET wasanswered = 'yes'  WHERE id = ?");
            stmt.setString(1, jsonObj.getString("topic"));
            stmt.setString(2, jsonObj.getString("category"));
            stmt.setString(3, jsonObj.getString("question"));
            stmt.setString(4, jsonObj.getString("answer"));
            stmt.setString(5, jsonObj.getString("profilepic"));
            stmt.setString(6, jsonObj.getString("url"));
            stmt.setInt(7, jsonObj.getInt("id"));

But im getting the following error

failureorg.postgresql.util.PSQLException: ERROR: syntax error at or near \"SET\"\n  Position: 170"

How can I be able to inert a table an update the other table at the same time?

You can do this using CTEs:

WITH i AS (
      INSERT INTO TRENDING ( TOPIC , CATEGORY , QUESTION , ANSWER , PROFILEPIC , TICK , URL )
          VALUES( ?, ? , ? , ? , ? , now() , ? ) 
          Returning ID 
     )
UPDATE QUESTBANK
    SET wasanswered = 'yes' 
    WHERE id IN (SELECT ID FROM i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM