简体   繁体   中英

SQL update set table if value in table A is equals to value in table B

this query is working fine.

UPDATE data
   SET unit_id='a3110a89'
 WHERE unit_id='7d18289f';

Now, I need to run this query over 30 times so I made csv file import it to the DB with this command:

COPY mytable FROM 'D:/test.csv' WITH CSV HEADER DELIMITER AS ','

Now I have table called my table with 2 columns OLD and NEW i want to search the table "data" in column unit_id anywhere there if the value equals to the value in table "mytable.old" replace it with the value "mytable.new" on the same row.

I tried to run this query but I get an error:

UPDATE data
   SET unit_id=(SELECT mytable."old" FROM public.mytable)
   WHERE unit_id=(SELECT mytable."new" FROM public.mytable)

error:

more than one row returned by a subquery used as an expression

I think i'm just trying to do it in the wrong way...

thx for the help!

by the way Im using PostgreSQL

Your subqueries need to be correlated to the outer update:

UPDATE data
   SET unit_id = (SELECT mytable."new" FROM public.mytable where data.old = mytable.old)
   WHERE unit_id in (SELECT mytable."old" FROM public.mytable);

That is, set the unit_id to the "new" value, when you find the "old" value in the table.

Can you try like this,

UPDATE data A
   SET A.unit_id=B.old
   FROM (SELECT mytable."old",mytable."new" FROM public.mytable) B
   WHERE A.unit_id=B.new
UPDATE data A
  SET unit_id = B."old"
  FROM public.mytable B
  WHERE A.unit_id = B."new"
  ;

BTW: it looks like you also have old and new swapped in your question. Do you really want A's value to be set to B's old field?

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