SQL/postgresql

[postgresql] 테이블 2개 update / update 여러 개 / update 여러개 / select해서 update / 서브쿼리 update / subquery update

도미노& 2021. 11. 17. 16:51

1. 테이블 2개 조건 걸어서 update 하는 방법
출처 https://otrodevym.tistory.com/entry/postgresqlupdate%EB%A5%BC-select%EB%A1%9C-%ED%95%98%EA%B8%B0

 

update 테이블A as t1 set
	amt = amt - t2.tot_amt
from 테이블B as t2
where t1.key_seq = t2.key_seq
and t1.company_code = t2.company_code
and ...

주의할 점 : set 다음의 테이블A의 amt에는 [ t1.amt ] 라고 쓰지 않는다.

 

 

 

2. 내가 하고자 했던 것은 select해서 데이터를 만든 후

그 데이터 값으로 update하는 것이기 때문에,

테이블B 자리에 괄호를 열어 원하는 데이터를 Select 했다.

구조는 1번과 동일하다.

update 테이블A as t1 set
	amt = amt - t2.tot_amt
from
(
	select
		max(key_seq) as key_seq
		, max(company_code) as company_code
		, sum(amt) as tot_amt
	from (
		select
			key_seq, amt
			, (select
					company_code
				from 유저테이블 user
				where cap.user_key = user.user_key
			) as company_code
		from 결제테이블 cap
		where trk_no in (
			운송장번호
		)
	) t1
	group by key_seq, company_code
) as t2
where t1.key_seq = t2.key_seq
and t1.company_code = t2.company_code

 

'SQL > postgresql' 카테고리의 다른 글

[postgresql] eclipse, mybatis 사용 round does not exist  (0) 2021.11.11
[postgresql] Lock 풀기  (0) 2021.08.31
[postgresql] uuid 생성 함수  (0) 2021.08.26