【问题标题】:How can I update a table that has struct inside a struct and both structs are inside an array? ARRAY<STRUCT<STRUCT>> [duplicate]如何更新在结构内具有结构且两个结构都在数组内的表?数组<STRUCT<STRUCT>> [重复]
【发布时间】:2021-01-04 21:25:26
【问题描述】:

我有一个具有以下数据结构的表:

id                    integer nullable
candidate             record  repeated
candidate.name        string  nullable
candidate.results     record  nullable
candidate.results.r1  integer nullable
candidate.results.r2  integer nullable

所以,基本上,它是一个具有结构的数组,并且在结构内部还有另一个结构。 像这样的:

[struct("jp" as name, struct(null as r1, null as r2) as results)] candidate

如何更新此结构?我用它创建了一些玩具数据,并使用cast(floor(2*rand()) as int64)candidate.results.r1 列分配了0 到1 之间的随机值。我想将candidate.results.r2 设置为另一个随机值candidate.results.r1 cast(floor(2*rand()) as int64) 其中candidate.results.r1 等于1。

我怎样才能做到这一点?


编辑: 好的,在查看 this 其他问题并成功运行此查询后,我设法“理解”(或者至少我认为我做到了):

update `mytable` t
set  candidate= array(
select as struct name,
(select as struct results.r1,
if(results.r1= 1,cast(floor(2*rand()) as int64),null) r2) results from t.candidate)
where true

我想知道为什么会这样?为什么不需要使用where 子句而只需将其设置为true?此外,为什么该查询有效但这个查询失败:

update `mytable` t
set  candidate= array(
select as struct name,
(select as struct results.r1,
if(results.r1= 1,cast(floor(2*rand()) as int64),null) results.r2) results from t.candidate)
where true

基本上,添加results 并使if statement if(results.r1= 1,cast(floor(2*rand()) as int64),null) results.r2 使查询无效。为什么?

【问题讨论】:

  • 有很多类似的帖子有答案 - 您是否尝试过先搜索一下?
  • 我进行了一些搜索并尝试了一些,但我无法使查询有效。通常我在数组中找到结构,但我还没有在数组中的结构中找到结构。也许你可以指出我正确的方向? :)
  • @MikhailBerlyant 添加了一个具有解决方案的编辑部分,我根据您提供的其他解决方案“推断”了它。如果您能向我解释这个的“原因”,将不胜感激。

标签: sql google-bigquery


【解决方案1】:

为什么需要使用 where 子句并将其设置为 true?

WHERE 子句是 UPDATE DML 的必备部分

每个 UPDATE 语句都必须包含 WHERE 关键字,后跟一个条件。
要更新表中的所有行,请使用 WHERE true。

基本上,添加结果并使 if 语句 if(results.r1= 1,cast(floor(2*rand()) as int64),null) results.r2 使查询无效。为什么?

您的第二个查询中的results.r2 是一个别名,因此它是无效的 - 您应该只使用r2(就像您的第一个查询中一样)

【讨论】:

  • 考虑也投票赞成答案:o)
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 2022-06-16
  • 1970-01-01
相关资源
最近更新 更多