我正在嘗試加入需要在三個不同列中基本匹配的兩個表,但其中一列可能在兩個表中都有空值。要加入的列將是 content_id、user_id 和 product_id,但兩個表中的產品可能相同也可能不同。讓我們看一個例子:
表A
| 內容 ID | 用戶身份 | 產品編號 | 點擊 | 已保存 |
|---|---|---|---|---|
| 96787244 | 4195813 | 4533700 | 3 | 0 |
| 96787244 | 4195813 | 4536767 | 4 | 2 |
| 96787244 | 4195813 | 5736767 | 3 | 0 |
表B
| 內容 ID | 用戶身份 | 產品編號 | 喜歡 | 共享 |
|---|---|---|---|---|
| 96787244 | 4195813 | 2103700 | 1 | 0 |
| 96787244 | 4195813 | 4536767 | 0 | 2 |
| 96787244 | 4195813 | 1100046 | 1 | 1 |
| 96787244 | 4195813 | 5736767 | 1 | 0 |
我需要我的決賽桌看起來像
| 內容 ID | 用戶身份 | 產品編號 | 點擊 | 已保存 | 喜歡 | 共享 |
|---|---|---|---|---|---|---|
| 96787244 | 4195813 | 4533700 | 3 | 0 | 空值 | 空值 |
| 96787244 | 4195813 | 2103700 | 空值 | 空值 | 1 | 0 |
| 96787244 | 4195813 | 4536767 | 4 | 2 | 0 | 2 |
| 96787244 | 4195813 | 1100046 | 空值 | 空值 | 1 | 1 |
| 96787244 | 4195813 | 5736767 | 3 | 0 | 1 | 0 |
我嘗試使用完全外連接 USING(content_id, user_id, product_id) 但并沒有真正起作用。
uj5u.com熱心網友回復:
似乎您正在尋找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<>在這里擺弄
uj5u.com熱心網友回復:
這是執行此操作的另一種方法。
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。不知道為什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/363535.html
