简体   繁体   English

BigQuery - 使用子查询和OR语句加入多个条件

[英]BigQuery - Joining on multiple conditions using subqueries and OR statements

Is there anyway to join two tables on multiple potential conditions? 无论如何在多个潜在条件下加入两个表格?

I'm currently migrating some code from Postgres to Bigquery where I joined on multiple potential values like: 我目前正在将一些代码从Postgres迁移到Bigquery,我加入了多个潜在的值,如:

SELECT
 *
FROM
 (
 SELECT
   offer_table.offer_id
   ,customer_table.customer_name
   ,customer_table.visit_count
   ,ROW_NUMBER() OVER (PARTITION BY offer_table.offer_id ORDER BY customer_table.visit_count DESC) AS customer_visit_rank
 FROM
   offer_table
   LEFT JOIN customer_table ON
    (
    offer_table.customer_id = customer_table.customer_id
    OR offer_table.email = customer_table.email
    OR offer_table.phone = customer_table.phone
    )
 ) dummy
WHERE
  customer_visit_rank = 1

I needed to this because my offer and customer data had inconsistent usage of our id, email, and phone fields but all were valid potential matches. 我需要这个,因为我的报价和客户数据对我们的ID,电子邮件和电话字段的使用不一致,但都是有效的潜在匹配。 If multiple fields worked (ex: id and email matched), there would be duplicate rows and I'd filter them out based on the row_number column after ranking using the ORDER BY section. 如果多个字段有效(例如:id和电子邮件匹配),则会有重复的行,我会在使用ORDER BY部分排序后根据row_number列过滤掉它们。

However when I try to join on multiple conditions in BigQuery, I get this error message: 但是当我尝试在BigQuery中加入多个条件时,我收到以下错误消息:

LEFT OUTER JOIN cannot be used without a condition that is an equality of fields from both sides of the join.

Has anyone figured out a solution to join on multiple values instead of doing the above? 有没有人想出一个加入多个值的解决方案而不是上面做的?

You can write separate queries, then use COALESCE : 您可以编写单独的查询,然后使用COALESCE

SELECT
  *
FROM
  (
    SELECT
      offer_table.offer_id
      ,COALESCE(c1.customer_name,c2.customer_name,c3.customer_name)
      ,COALESCE(c1.visit_count,c2.visit_count,c3.visit_count)
      ,ROW_NUMBER() OVER (PARTITION BY offer_table.offer_id ORDER BY customer_table.visit_count DESC) AS customer_visit_rank
    FROM
      offer_table
    LEFT JOIN customer_table c1
      ON offer_table.customer_id = customer_table.customer_id
    LEFT JOIN customer_table c2
      ON offer_table.email = customer_table.email
    LEFT JOIN customer_table c3
      ON offer_table.phone = customer_table.phone
   )
 ) AS dummy
WHERE
  customer_visit_rank = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM