【问题标题】:Simple sql-merge简单的 sql 合并
【发布时间】:2021-08-26 10:44:59
【问题描述】:

我通常很高兴使用 sql 合并(使用 google bigquery 及其 sql 版本,但我认为这个问题是通用的)。但是,我有一个我无法通过合并解决的用例。

我有一个源表 s 和一个目标表 t。他们都有一个名为“day”的字段。我想从 t 中删除所有包含 s 中的日期的行。然后我想在 t 中插入 s 中的所有行。

不使用合并,我可以使用两个语句来完成:

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.

有人可以帮忙吗?这似乎是一个非常简单的操作,但我根本无法编写正确的合并语句。

【问题讨论】:

    标签: sql merge google-bigquery


    【解决方案1】:

    我认为使用合并不是一个合适的场景。但是,如果您使用 UNION,这将非常容易。

    你基本上选择 t 中没有出现在 s 中的所有行,然后附加 s 的所有行。

    select * from t where day not in (SELECT distinct(day) from s)
    UNION ALL select * from s
    

    【讨论】:

    • 嘿,这是一个很好的解决方案。谢谢!
    【解决方案2】:

    不幸的是,BigQuery 中的 WHEN 子句 are not supported for MERGE statements 中的子查询。有一个开放的feature request 与一个similar scenario 和一个workaround 可能对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-16
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 2020-08-17
      • 2019-03-24
      相关资源
      最近更新 更多