Update multiple row with different value in same PostgreSQL query

讓 PostgreSQL 在一次 Query 中更新多筆資料,並且給予不同的值

範例

  • Table avatars
name jobtypeid job_rank job_name
megumin 1 40 magician
kazuma 2 10 thief
  • 根據不同的 job_type_id 來更新 job_rankjob_name
UPDATE avatars AS a SET
    job_rank = new.job_rank,
    job_name = new.job_name
FROM (VALUES
    (1, 10, 'explosion expert'),
    (2, 1, 'kuzuma')
) AS new(job_type_id, job_rank, job_name)
WHERE new.job_type_id = a.job_type_id;
  • 更新後的 table avatars
name jobtypeid job_rank job_name
megumin 1 10 explosion expert
kazuma 2 1 kuzuma
© 2019 Hau Chen