okinawa

ITと英語の勉強メモがメイン

【SQL】SELECT結果を使ってUPDATEする

基本のUPDATE文

 UPDATE
 テーブル名
 SET
 列名1 = 値1
,列名2 = 値2
 WHERE
[条件];

2種類の方法

テーブル結合

・構文

UPDATE テーブル名1
INNER JOIN (
SELECT * FROM テーブル名2
WHERE
[条件]
) AS sub
ON 
[テーブル結合条件]
SET 
テーブル名1.列名1 = sub.列名1

更新対象のテーブルに対して、サブクエリを結合する。

サブクエリではなく、普通のテーブル結合も可能。

table2更新前

・使用例

上記のtable2のvalue777を888に更新する。

update table2
inner join (
select *, 888 as sample from table2
where
value = 777
) AS sub
on 
main.tenpo = sub.tenpo
and main.date = sub.date
and main.bunrui = sub.bunrui
and main.value = sub.value
and main.updatecheck = sub.updatecheck
set 
table2.value = sub.sample

tabel2更新後

UPDATE FROM

UPDATE FROMは今のところ、SQLServerとPostgreでしか使えないらしい。

update table2
set
value = sub.sample
from (
select *, 888 as sample from table2
where
value = 777
) as sub
where
table2.tenpo = sub.tenpo
and table2.date = sub.date
and table2.bunrui = sub.bunrui
and table2.value = sub.value
and table2.updatecheck = sub.updatecheck

From句の後にサブクエリを書く。

From句の後にサブクエリでなく、普通のテーブル参照も可能。

参考

qiita.com

learn.microsoft.com