developer tip

조건에 따라 다른 테이블의 열로 열 값 업데이트

copycodes 2020. 8. 17. 09:13
반응형

조건에 따라 다른 테이블의 열로 열 값 업데이트


두 개의 테이블이 있습니다 ...

table1 (id, item, price) 값 :

id | item | price
-------------
10 | book | 20  
20 | copy | 30   
30 | pen  | 10

.... table2 (id, item, price) 값 :

id | item | price
-------------
10 | book | 20
20 | book | 30

이제 다음을 원합니다.

update table1 
   set table1.Price = table2.price 
 where table1.id = table2.id
   and table1.item = table2.item.

어떻게하나요?


다음과 같이해야합니다.

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

다음을 시도해 볼 수도 있습니다.

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

이것은 확실히 작동합니다.

UPDATE table1
SET table1.price=(SELECT table2.price
  FROM table2
  WHERE table2.id=table1.id AND table2.item=table1.item);

참고 URL : https://stackoverflow.com/questions/1746125/update-columns-values-with-column-of-another-table-based-on-condition

반응형