简单 sql-合并
Simple sql-merge
我通常很乐意使用 sql 合并(使用 google bigquery 及其 sql 版本,但我认为这个问题很普遍)。但是,我有一个用例无法通过合并解决。
我有一个源 table s 和一个目标 table t。他们都有一个名为 'day' 的字段。我想从 t 中删除所有包含 s 中包含的日期的行。然后我想将 s 中的所有行插入到 t.
不使用合并,我可以使用两个语句来完成:
delete from t where day in (select day from s);
insert into t (select * from s);
但是,我想使用合并将其作为单个语句来完成。
我最大的努力是这个
merge t
using s
on false
when not matched by target then
insert row
when not matched by source and t.day between
(select min(day) from s) and (select max(day) from s)
then delete
只要 s 中的日期形成一个连续的间隔,这就可以正常工作。然而,对于任意日期,它显然从 t 中删除了太多。我试过了
merge t
using s
on false
when not matched by target then
insert row
when not matched by source and t.day in
(select day from s)
但是 bigquery 中不允许最后的子查询。我收到错误
google.api_core.exceptions.BadRequest: 400 Correlated Subquery is unsupported in WHEN clause.
有人能帮忙吗?这看起来是一个非常简单的操作,但我一直无法编写正确的合并语句。
我认为不适合使用merge。但是如果你使用 UNION 就很容易了。
你基本上 select t 中哪一天没有出现在 s 中的所有行,然后追加 s 的所有行。
select * from t where day not in (SELECT distinct(day) from s)
UNION ALL select * from s
不幸的是,WHEN 子句中的子查询 are not supported for MERGE statements in BigQuery. There's an open feature request with a similar scenario and a workaround 可能对您有所帮助。
我通常很乐意使用 sql 合并(使用 google bigquery 及其 sql 版本,但我认为这个问题很普遍)。但是,我有一个用例无法通过合并解决。
我有一个源 table s 和一个目标 table t。他们都有一个名为 'day' 的字段。我想从 t 中删除所有包含 s 中包含的日期的行。然后我想将 s 中的所有行插入到 t.
不使用合并,我可以使用两个语句来完成:
delete from t where day in (select day from s);
insert into t (select * from s);
但是,我想使用合并将其作为单个语句来完成。 我最大的努力是这个
merge t
using s
on false
when not matched by target then
insert row
when not matched by source and t.day between
(select min(day) from s) and (select max(day) from s)
then delete
只要 s 中的日期形成一个连续的间隔,这就可以正常工作。然而,对于任意日期,它显然从 t 中删除了太多。我试过了
merge t
using s
on false
when not matched by target then
insert row
when not matched by source and t.day in
(select day from s)
但是 bigquery 中不允许最后的子查询。我收到错误
google.api_core.exceptions.BadRequest: 400 Correlated Subquery is unsupported in WHEN clause.
有人能帮忙吗?这看起来是一个非常简单的操作,但我一直无法编写正确的合并语句。
我认为不适合使用merge。但是如果你使用 UNION 就很容易了。
你基本上 select t 中哪一天没有出现在 s 中的所有行,然后追加 s 的所有行。
select * from t where day not in (SELECT distinct(day) from s)
UNION ALL select * from s
不幸的是,WHEN 子句中的子查询 are not supported for MERGE statements in BigQuery. There's an open feature request with a similar scenario and a workaround 可能对您有所帮助。