0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【PostgreSQL】同じテーブルをアップデートする【備忘録】

Last updated at Posted at 2023-10-25

業務で詰まったので備忘録としてメモ

やりたいこと

別のテーブルを参照し、条件作成の上、同じテーブルをアップデートする。

TABLE_Aの全レコードを対象に
TABLE_A.id = TABLE_B.idが成立する場合
TABLE_B.column_AをTABLE_A.column_AにUPDATEする。

※成立しない場合は任意の値でUPDATE

クエリ例

query
UPDATE TABLE_A
SET column_A = coalesce(TABLE_B.column_A,'任意の値')
FROM TABLE_A AS main_table
INNER JOIN TABLE_B AS sub_table
    ON main_table.id = sub_table.id
WHERE
TABLE_A.主キー = main_table.主キー
--(主キーが複数個ある場合はそれらすべてをWHERE句に記載)

UPDATE対象とFROM句に記載するテーブルが同じ場合
主キー同士をリンクさせる必要がある。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?