LoginSignup
3
3

More than 5 years have passed since last update.

Postgresでまとめて複数のカラムをupdateをする方法

Last updated at Posted at 2014-10-08

postgresのfrom句

  • postgresにはfromlistというものがある。
  • 下の例のようにaccountsのtableの条件からwhere要素やselect要素の値を変更することができる
UPDATE
  employees
SET
  sales_count = sales_count + 1
FROM
  accounts
WHERE
  accounts.name = 'Acme Corporation'
AND
  employees.id = accounts.sales_person;

sqlの中にテンポラリのデータテーブルを作って利用する

select * from (SELECT unnest(ARRAY['a','b']) as a, unnest(ARRAY[2,3]) as b) AS t;
a b
a 2
b 3

(2 rows)

テンポラリのテーブルを埋め込んで更新するとかどうだろう

  • 上の二つを応用したら、updateを同時に行うことがpostgresでできる。
UPDATE
  employees
SET
  sales_count = sales_count + 1
FROM
  select * from (SELECT unnest(ARRAY['a','b']) as name, unnest(ARRAY[2,3]) as sales_person) AS accounts;
WHERE
  accounts.name = 'Acme Corporation'
AND
  employees.id = accounts.sales_person;

参考

3
3
2

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
3
3