首页 > 解决方案 > SQL合并查询中需要过滤目标表

问题描述

我正在使用 BigQuery SQL 来执行合并查询。这是查询

MERGE `dataset.target_table` AS Target
USING
    (
        select
            *
        from
            `dataset.source_table` s_data
        WHERE
            trans_id is not null and user_id is not null
    )
AS Source
ON Source.trans_id = Target.trans_id and Target.start_date IN 
    (
        select distinct start_date from `dataset.source_table`
    )
WHEN NOT MATCHED BY Target THEN
    INSERT (...)
    VALUES (...)
WHEN MATCHED and Target.user_id is null THEN
    UPDATE SET ...

我在 ON 语句中使用子查询时遇到问题。In Subquery not supported by join predicate

我有这个子查询的原因是因为我想在 Merge 发生或 bigquery 引发 OOM 异常之前过滤 Target 表。目标表是 100 亿行,而源表是 200m 行。我不需要 ON 语句中的子查询,但这是一种在合并发生之前基本上过滤目标表的 hacky 方法。我可以采取其他方法吗?

我在这里尝试了这种方法 - https://dba.stackexchange.com/questions/30633/merge-a-subset-of-the-target-table利用

WITH TARGET AS 
(
    SELECT * 
    FROM `dataset.target_table`
    WHERE <filter target_table here>
)
MERGE INTO TARGET
...

但似乎 BigQuery 不支持这并给出了语法错误。如何在合并发生之前过滤我的目标表,这样它就不需要将整个表加载到内存中?

标签: sqlgoogle-bigquery

解决方案


我有点困惑。你start_date能从匹配的行中取出source吗?

MERGE `dataset.target_table` AS Target USING
       (select *
        from `dataset.source_table` s_data
        WHERE  trans_id is not null and user_id is not null
       ) AS Source
       ON Source.trans_id = Target.trans_id and
          Target.start_date = source.start_date 

推荐阅读