2016-09-02 17 views
1

2つのテーブルがあり、2つの更新を書きたいと思います。
id、flag(null)、およびcount(null)カラムを持つtbl_stage。
id、count、更新された列を持つ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 




もう1つ、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つのUPDATEステートメントを使用して、1つのステートメント内の2つのテーブルを更新できないようにする必要があります。

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); 

countが予約語に、ので、(私は、列名のcntを選びました

+0

これは10分ごとに100万行単位で更新するための良い考えですか? –

+0

@RedshiftGuy:あなたはそれを頼んだ...いいアイデアかどうかは分からない。 –

関連する問題