简体   繁体   中英

How to update records based from another table in Postgres

I have two tables in Postgres

TableA
id, item_id, parent_id
1     i1        null
2     i2         1 -> match the id of the first record (1)
3     i3         2 -> match the id of the second record (2)

TableB
parent_id, item_id
  null           i1
   i1            i2         
   i2            i3

i1 is the top level, i2 is the second level and i3 is the third level.

I need to update the parent_id column in table A to have 1 and 2 based on the table B .

I have

Update TableA set parent_id = ? (SELECT id from TableA WHERE TableA.item_id = TableB.parent_id)
from TableB
where TableB.parent_id = TableA.item_id

The above is basically what I need but I am not sure the exact systax to do it. Can anyone help?

Thanks a lot!

What I think (your not very clear) you want is something like this(not tested):

Update TableA set parent_id = TableA_parent.id
from TableB
inner join TableA TableA_parent
  on TableB.parent_id = TableA_parent.item_id
where TableB.item_id = TableA.item_id

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