【问题标题】:Full Outer Joins with in Multiple columns多列中的完全外连接
【发布时间】:2022-01-01 08:53:11
【问题描述】:

我正在尝试连接两个需要在三个不同列中基本匹配的表,但其中一列可能在两个表中都有空值。要加入的列将是 content_id、user_id 和 product_id,但两个表中的产品可能相同也可能不同。我们来看一个例子:

表 A

Content_id User_ID Product_ID Clicked Saved
96787244 4195813 4533700 3 0
96787244 4195813 4536767 4 2
96787244 4195813 5736767 3 0

表 B

Content_id User_ID Product_ID Liked Shared
96787244 4195813 2103700 1 0
96787244 4195813 4536767 0 2
96787244 4195813 1100046 1 1
96787244 4195813 5736767 1 0

我需要我的决赛桌看起来像

Content_id User_ID Product_ID Clicked Saved Liked Shared
96787244 4195813 4533700 3 0 NULL NULL
96787244 4195813 2103700 NULL NULL 1 0
96787244 4195813 4536767 4 2 0 2
96787244 4195813 1100046 NULL NULL 1 1
96787244 4195813 5736767 3 0 1 0

我尝试使用完全外连接 USING(content_id, user_id, product_id) 但并没有真正起作用。

【问题讨论】:

  • 为什么它真的不起作用?你得到了什么?这当然是正确的做法。
  • 作为 1、2 和 3 的样本数据比 4533700、4536767 和 4532700 容易得多。
  • 我猜您在执行此操作时会在 content_ID 、 user_ID 和 product_ID 上得到空值,并且不想为不同的表重复字段名称......所以合并这些值......你需要SELECT coalesce(TableA.Content_ID,TableB.ContentID) as Content_ID, coalesce(TableA.User_ID, TableB.userID) as User_ID... 我会让你弄清楚product_ID ......正如蒂姆所说,你的方法是可靠的。但是您的问题没有明确定义,因此我们不知道您为什么要苦苦挣扎。

标签: sql snowflake-cloud-data-platform dbt


【解决方案1】:

好像你在找full join

select
    coalesce(t1.Content_id, t2.Content_id) Content_id,
    coalesce(t1.User_ID, t2.User_ID) User_ID,
    coalesce(t1.Product_ID, t2.Product_ID) Product_ID,
    t1.Saved,
    t1.Clicked,
    t2.Liked,
    t2.Shared
from table1 t1 
full outer join table2 t2 
    on t1.Content_id = t2.Content_id
    and t1.User_ID = t2.User_ID
    and t1.Product_ID = t2.Product_ID

db小提琴here

【讨论】:

    【解决方案2】:

    这是另一种方法。

    SELECT a.*, b.liked, b.shared
    FROM a NATURAL LEFT JOIN b
    UNION
    SELECT b.content_id, b.user_id, b.product_id, a.clicked, a.saved, b.liked, b.shared
    FROM a NATURAL RIGHT JOIN b;
    

    我们要枚举第二部分的列,因为它自然会先选择所有b,而UNION不会排列对应的列。

    Postgres 不接受 NATURAL FULL JOIN。不知道为什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-02
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多