目錄
0. 其他
1. 問題描述
2. 問題復現
2.1. 建表陳述句
2.2. 插入資料
2.3. 查詢SQL以及問題
3. 問題原因
4. 問題解決
0. 相關文章鏈接
開發隨筆文章匯總
1. 問題描述
在Hive中(其他類似SQL,比如PostgreSQL可能也存在此問題),當對多張表(3張及以上)進行full join時,會存在每張表的主鍵都是唯一,但當full join后,會發現主鍵可能有重復,
2. 問題復現
2.1. 建表陳述句
create table realtime_dw.table_a
(
id int,
name int
);
create table realtime_dw.table_b
(
id int,
name int
);
create table realtime_dw.table_c
(
id int,
name int
);
2.2. 插入資料
-- a表 -- b表 -- c表
1,111 1,111 1,111
2,222 3,333 4,444
3,333 4,444 5,555

2.3. 查詢SQL以及問題
select
coalesce(a.id, b.id, c.id) as id
, a.name
, b.name
, c.name
from table_a as a
full join table_b as b
on a.id = b.id
full join table_c as c
on a.id = c.id
;
當執行如上查詢SQL時,會發現其中 id = 4 的資料有重復,如下圖所示:

3. 問題原因
之所以會出現這樣的問題,是因為是以a表為主表,但a表中只有 id 為 1、2、3 的資料,但在b表中有id為4,c表中也有id為4,此時full join時,a表會以空值和b表、c表中id為4的資料join,這樣關聯后的表中就會出現2條id為4的資料,
4. 問題解決
在后續的表full join時,不單單使用第一張表的主鍵full join(因為是full join,所以肯定會存在第一張表為null,而其他表有值的資料),而使用 coalesce 方法對所有前面已經full join了的主鍵進行條件關聯,如下代碼:
select
coalesce(a.id, b.id, c.id) as id
, a.name
, b.name
, c.name
from table_a as a
full join table_b as b
on a.id = b.id
full join table_c as c
on coalesce(a.id, b.id) = c.id
;
此時,結果就不會有主鍵重復,如下查詢結果所示:

注:其他相關文章鏈接由此進 -> 開發隨筆文章匯總
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/420475.html
標籤:其他
上一篇:RabbitMQ 超詳細入門篇
下一篇:ElasticSearch
