2016-09-02 2 views
1

2 개의 테이블이 있으며 2 개의 업데이트를 작성하려고합니다.
id, flag (null) 및 count (null) 열이있는 tbl_stage.
id, count, updated 열이있는 tbl_source입니다. 갱신업데이트 2 다른 테이블의 값을 기반으로하는 열

내가 tbl_stage.count = tbl_source.count 및 tbl_stage.flag = 사실 tbl_stage.id = tbl_source.id를 업데이트 할
tbl_stage     tbl_source 
id flag count  id count updated 
abc NULL NULL  abc 9.0  false 
          def 3.6  false 

전에

.
또 다른 tbl_source.updated = true 여기서 tbl_stage.id = tbl_source.id.

업데이트 후 다음과 같이 표시되어야합니다.

tbl_stage     tbl_source 
id flag count  id count updated 
abc true 9.0   abc 9.0  true 
          def 3.6  false 
+1

버전 전후의 샘플 테이블 데이터를 추가하십시오. 또한 사용중인 dbms에 태그를 지정하고 그 중 일부는 해당 업데이트에 대해 약간 다른 구문을 사용합니다. – jarlh

+0

제안 된대로 @jarlh 완료 –

+0

우수! (너무 나쁘게 Postgresql을 잘 모른다.) – jarlh

답변

0

한 명령문에서 2 개의 테이블을 업데이트 할 수 없으므로 2 개의 UPDATE 문을 사용해야합니다.

update tbl_stage 
set [count]=tbl_source.count 
    ,flag = 1 
FROM tbl_source WHERE tbl_stage.id=tbl_source.id 

update tbl_source 
set updated = 1 
from tbl_source WHERE tbl_stage.id=tbl_source.id 
and tbl_stage.count=tbl_source.count 
+1

*** FROM 목록에서 대상 테이블을 반복하지 않습니다 ***. 그러면 교차 결합이 생성됩니다. 'tbl_source의 업데이트 tbl_stage는 어디에서 ....'입니까? –

+0

@a_horse_with_no_name 당신은 tbl_stage를 업데이트해야 함을 의미합니다. tbl_stage.count = tbl_source.count를 설정하십시오. , tbl_stage.flag = 1 tbl_stage.id = tbl_source.id에 내부 참여 tbl_source를 설정 하시겠습니까? –

+0

@santosh - 이전 업데이트 쿼리와 마찬가지로 내부 조인을 사용할 수 있습니까? –

0
당신은 한 번에 두 테이블을 변경, 하나의 문이 작업을 수행 할 수 있습니다

:


with stage_update as (
    update stage 
    set cnt = s.cnt, 
     flag = true 
    from source s 
    where stage.id = s.id 
    returning s.id 
) 
update source 
    set updated = true 
where id in (select id from stage_update); 
(나는 열 이름을 cnt을 선택 count가 예약어이기 때문에, 그리고 식별자로 사용하면 안 됨)

+0

10 분마다 백만 개의 행을 업데이트하는 것이 좋습니까? –

+0

@RedshiftGuy : 당신이 요청했습니다 ... 좋은 생각인지 나는 말할 수 없습니다. –

관련 문제