简体   繁体   English

基于PostgreSQL中的varchar数组更新表的列

[英]Update column of a table based on array of varchar in PostgreSQL

I have a table to which i have added a column varchar colorcode. 我有一个表,我在该表中添加了列varchar颜色代码。

The table already has many rows. 该表已经有很多行。 state of table after adding colorcode column is 添加colorcode列后表格的状态为

id   name               location     colorcode
121  Royal Challengers  Bangalore     
122  Sun Risers         Hyderabad
123  Dare Devils        Delhi
124  Gujrat Lions       Ahmadabad

I have a array of color codes 我有一系列颜色代码

 ["#FF8484", "#FF82A9", "#FA82FF", "#C682FF", "#8782FF"]

For each row in the table I must update the colorcode column by matching index of array with (row_number() - 1). 对于表中的每一行,我必须通过将数组的索引与(row_number()-1)进行匹配来更新colorcode列。

I have dealt with list of values when using "in" clause. 使用“ in”子句时,我已经处理了值列表。

example: 例:

select * from table where id in(1,2,3,4) etc

here 1,2,3,4 is nothing but a array 这里1,2,3,4只是一个数组

I want to update the colorcode column on similar lines but I don't know how to access the elements of my array based in index. 我想在相似的行上更新colorcode列,但是我不知道如何访问基于索引的数组元素。

after running the update statement my expected output is 运行更新语句后,我的预期输出是

id   name               location     colorcode
121  Royal Challengers  Bangalore     #FF8484
122  Sun Risers         Hyderabad     #FF82A9
123  Dare Devils        Delhi         #FA82FF
124  Gujrat Lions       Ahmedabad     #C682FF

I can sort the result based on id ie., the primary key 我可以根据ID(即主键)对结果进行排序

Note: I am using Postgres 注意:我正在使用Postgres

You could do it as follows. 您可以按照以下步骤进行操作。 I assume your table is called t : 我假设您的表名为t

update t
set    colorcode = middle.cc
from   (
        select id, ('{#FF8484,#FF82A9,#FA82FF,#C682FF,#8782FF}'::text[])[rn] as cc
        from   (select id, row_number() over (order by id) as rn from t) as base
        where  rn <= 5
       ) as middle
where middle.id = t.id;

In the most inner query ( base ), the row number is retrieved for each record in the table. 在最内部的查询( base )中,为表中的每个记录检索行号。 Then in the middle query ( middle ) that row number is used to fetch the corresponding colour code from an in-line array of text elements. 然后,在中间查询( middle )中,该行号用于从文本元素的嵌入式数组中获取相应的颜色代码。 Finally the update statement joins that result with the table t again, by its id , in order to store that colour code. 最后,update语句通过其id再次将该结果与表t连接起来,以存储该颜色代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM