数组中每个元素的PostgreSQL更新字段

时间:2019-03-04 06:59:40

标签: sql postgresql

我希望在SQL中执行以下任务:

我有一个带有列的表: uuid(uuid),单词(文本),wordList(文本[]),uuidList(uuid [])

我有wordList数组,uuid和word列填充。我希望像这样更新并填充uuidList:

foreach element in wordList
    var x = select uuid where word = element;
    uuidList.append(x);

示例: 我有一张这样的桌子:

+---------+-------+--------------------+----------+
|  uuid   | word  |      wordList      | uuidList |
+---------+-------+--------------------+----------+
| aaaa... | hello | NULL               | NULL     |
| bbbb... | world | NULL               | NULL     |
| cccc... | blah  | {'hello', 'world'} | NULL     |
+---------+-------+--------------------+----------+

我希望它变成这样:

+---------+-------+--------------------+--------------------+
|  uuid   | word  |      wordList      |      uuidList      |
+---------+-------+--------------------+--------------------+
| aaaa... | hello | NULL               | NULL               |
| bbbb... | world | NULL               | NULL               |
| cccc... | blah  | {'hello', 'world'} | {aaaa..., bbbb...} |
+---------+-------+--------------------+--------------------+

我对SQL还是很陌生,并且对如何做感到困惑。我认为我无法将表格加入自身。我不知道我是否应该在临时表中存储信息以某种方式实现这一目标(我读过的一些相关问题都提出了这一建议)...

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在一条语句中汇总所有需要的UUID:

select w1.uid, array_agg(w2.uid order by wl.idx) as uuidlist
from words w1
  cross join lateral unnest(w1.wordlist) with ordinality as wl(word,idx) 
  join words w2 on w2.word = wl.word
where w1.wordlist is not null
  and w1.uuidlist is null -- optional
group by w1.uid;

选项with ordinality返回一个附加列,该列指示元素在原始数组中的位置。需要以正确的顺序聚合UUID。

这将返回以下结果以及您的示例数据:

uid  | uuidlist  
-----+------------
cccc | {aaaa,bbbb}

这可以用作更新语句的源(假设列uid是唯一的):

update words
  set uuidlist = t.uuidlist
from (
  select w1.uid, array_agg(w2.uid order by wl.idx) as uuidlist
  from words w1
    cross join lateral unnest(w1.wordlist) with ordinality as wl(word,idx)
    join words w2 on w2.word = wl.word
  where w1.wordlist is not null
    and w1.uuidlist is null -- optional
  group by w1.uid
) t
where t.uid = words.uid;

在线示例:https://rextester.com/LZUYC57184

(请注意,在该示例中,数组的显示有点奇怪)