如何在BQ中更改struct数组中的值

时间:2018-06-01 18:49:00

标签: google-bigquery

我还没有理解(我不知道)如何将颜色“黄色”更新为“蓝色”并将其ID更新为5.解决这个例子将有助于我理解。感谢

--create or replace table mydataset.struct_4 (boxes string,colors array<struct<colour string,id int64>>)
--insert into mydataset.struct_4 (boxes,colors) values("box_1",[("brown",1),("green",3),("white",7)]),("box_2",[("yellow",2),("white",4)])
select * from `mydataset.struct_4` 

1 个答案:

答案 0 :(得分:2)

   
#standardSQL
SELECT 
  boxes, 
  ARRAY(
    SELECT AS STRUCT 
      IF(colour = 'yellow', 'blue', colour) colour, 
      IF(colour = 'yellow', 5, id) id
    FROM UNNEST(colors)
  ) colors
FROM `mydataset.struct_4` 

上述变化将是

#standardSQL
SELECT 
  boxes, 
  ARRAY(
    SELECT IF(colour = 'yellow', 
      STRUCT<colour STRING,id INT64>('blue', 5), 
      STRUCT(colour, id)) 
    FROM UNNEST(colors)
  ) colors
FROM `mydataset.struct_4`   

具有相同的课程输出

Row boxes   colors.colour   colors.id    
1   box_1   brown           1    
            green           3    
            white           7    
2   box_2   blue            5    
            white           4    
  

更新:但如何更新颜色&#34;黄色&#34;到&#34;蓝&#34;并使用UPDATE DML语句将其id设置为5:

#standardSQL
UPDATE `mydataset.struct_4` SET colors = ARRAY(
    SELECT IF(colour = 'yellow', 
        STRUCT<colour STRING,id INT64>('blue', 5), 
        STRUCT(colour, id)) 
    FROM UNNEST(colors)
) WHERE TRUE