如何在 Snowflake 的左外连接期间提取所有值(甚至是那些不匹配的值)?

How to pull all values (even those that don't match) during a left outer join in Snowflake?

我有两个 tables(table a 是 130 万行,table b 是 30 万行)我想加入电子邮件地址。但是,table b 中只有 1/3 的地址与 table a 匹配。理想情况下,输出应该是 col1 中 table a 的长度,col2 将是 table b 中的所有 300k 行,而 col3 将根据 col1 & 说 'mapped' 或 'not mapped'是否填充 col2。

我想显示来自 table b 的所有地址(甚至那些与 table a 不匹配的地址)和 table a 的第三列显示它们匹配或者他们没有。现在它只显示为 NULL。

如何在 SQL 中执行此操作?当前使用左外连接但可能需要使用完全连接?

SELECT DISTINCT TABLEA.EMAIL, TABLEB.EMAIL_ADDRESS FROM "db_tablea" TABLEA
left outer JOIN
"db_tableb" TABLE B
ON TABLEA.EMAIL = TABLEB.EMAIL_ADDRESS
CASE WHEN EMAIL IS NULL AND EMAIL_ADDRESS IS NOT NULL THEN 'NOT_MAPPED'
WHEN EMAIL IS NOT NULL AND EMAIL_ADDRESS IS NOT NULL THEN 'MAPPED'
ELSE 'REVIEW'
END AS MAPPED_FLAG
ORDER BY EMAIL
;

我会使用 exists 和一个相关的子查询:

select a.*, 
    case when exists (select 1 from tableb b where b.email_address = a.email)
        then 'mapped'
        else 'not mapped'
    end as review
from tablea a

这会为第一行 table 中的每一行生成一行,并带有一个标志,指示电子邮件是否存在于第二行 table。

一个特点是第一个 table 中的行在第二个 table 中有多个匹配项,但在结果集中不会“相乘”。

SELECT
    a.email
    ,b.email
    ,CASE WHEN a.email = b.email THEN 'MAPPED' ELSE 'NOT MAPPED' END status
FROM
    table_a a
    FULL OUTER JOIN table_b b ON (a.email = b.email)
;

https://www.db-fiddle.com/f/sWn6RS8GsfRhj5oXwS3Dso/0

允许更深入地了解不匹配的记录的细微变化

select t1.email, 
       t2.email_address, 
       case when t1.email is null then 'a not mapped to b' 
            when t2.email_address is null then 'b not mapped to a' 
            else 'mutually mapped' end as mapping_flag
from table_a t1 
full join table_b t2 on t2.email_address = t1.email;