是否可以按给定顺序设置column1 = ARRAY WHERE column2 = ARRAY

时间:2016-06-29 10:43:44

标签: arrays postgresql

这就是我的表格:

  word | key
_______________
       |   helicopter
       |   mamal
       |   cat
       |   bull
       |   bull
       |   bull
       |   mamal

这就是我想要的结果:

   word | key
________________
airplane|   helicopter
  bird  |   mamal
  dog   |   cat
  cow   |   bull
  cow   |   bull
  cow   |   bull
  bird  |   mamal

我不想使用像这样的4个更新

UPDATE table
SET word = 'airplane'
WHERE key = 'helicopter';

UPDATE table
SET word = 'bird'
WHERE key = 'mamal';

UPDATE table
SET word = 'cow'
WHERE key = 'bull';

UPDATE table
SET word = 'dog'
WHERE key = 'cat';

而是一个查询,在一个或两个数组中定义了数字 - 字对......这样的事情:

UPDATE table
SET word = ARRAY['airplane','bird','cow','dog']
WHERE number = ARRAY['helicopter','mamal','bull','cat'];

所以,问题是:是否有可能将值“飞机”赋予列字WHERE列key ='helicopter',将值'bird'赋值为列字WHERE列key ='mamal',等等,给定order ...所以我可以根据列键填充列字。

这是我关于stackoverflow的第一个问题,请原谅可能的问题缺陷,以及大量的编辑......谢谢

2 个答案:

答案 0 :(得分:2)

这将适用于PostgreSQL 9.5:

UPDATE "table"
SET word = (ARRAY['airplane', 'bird', 'cow', 'dog'])[
              array_position(
                 ARRAY['helicopter', 'mamal', 'bull', 'cat'],
                 key::text
              )
           ];

答案 1 :(得分:0)

如果不是问题那么你可以创建“真正的”字典表(可能是临时的)并将其与update语句一起使用:

update table t set 
  word = d.value 
from dict_table d where d.key = t.key;

或者,使用CTE,而不创建额外的表:

with dict_table(key, value) as (values
  ('helicopter','airplane'),
  ('mamal','bird'),
  ...)
update table t set 
  word = d.value 
from dict_table d where d.key = t.key;

如果有问题,那么您可以使用JSONB:

update table t set 
  word = '{
    "helicopter": "airplane", 
    "mamal": "bird", 
    "bull": "cow",
    "cat": "dog"}'::jsonb->>key.