Search code examples
sqlpostgresqlcursor

After inserted selected fields from one table to another, how to insert/update new records?


I can insert selected fields from Table A to Table B, with INSERT INTO Table B(planid, testno, sd, testname) VALUES (%s, %s, %s, %s);, SQL = "select * from Table A"and cursor.execute(SQL), but table A will have new records at any time, how to insert new records and update old records? Really appreciate for any advice.


Solution

  • ----First update existing records:

    update tableb set testno=t2.testno, sd=t2.sd, testname=t2.testname from tableb t1 inner join tablea t2 where t1.planid=t2.planid

    ----Insert new records insert into tableb select * from tablea where planid not in(select planid from tableb)