left join on 篩選與where篩選的比較
阿新 • • 發佈:2021-01-17
技術標籤:大資料處理hadoop/spark特徵工程與資料分析hivesqlmysql
join on後面也能進行條件篩選,where後面也能加條件進行篩選,但兩者的結果是不一樣的。下面通過實際資料案例來說明問題。
資料準備:
建表與寫入資料
A 表
hive >create table tempTableAzw(id int,name string ,grade int ,dept int ) ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'; hive >load data local inpath '/data0/VR/Compare7AndTotal/tempTableAzw.txt' into table tempTableAzw;
tempTableAzw.txt檔案形如:
1|lijie1|100|10
2|lijie2|90|20
3|lijie3|60|10
4|lijie4|80|10
5|lijie5|70|20
B表
create table tempTableBzw(id int ,name string ) row format delimited fields terminated by "|";
load data local inpath "/data0/VR/Compare7AndTotal/tempTableBzw.txt" into table tempTableBzw;
tempTableBzw.txt檔案形如
10 IT1
20 IT2
join on 後面進行條件篩選
A表與B表進行left join
select A .id ,A.name ,A.grade,A.dept,B.id,B.name
from tempTableAzw A left outer join tempTableBzw B
-- 上面outer 其實可以省略
on A.dept =B.id and A.grade >=80;
結果為
注意上結果圖中不符合on 後面的條件的行,B的值為NULL! 如果on 後面不帶 and A.grade >=80 這個條件,結果為
結論: 當把過濾條件寫在left join on 上面,會讓基表所有資料都能顯示,不滿足的右表會以null 填充。
如果將上面的left join 改為join 則顯示如下。同下面的where 結果一致。
篩選大於80的這個條件放到where 後面
程式碼
select A .id ,A.name ,A.grade,A.dept,B.id,B.name
from tempTableAzw A left join tempTableBzw B
on A.dept =B.id
where A.grade >=80;
結果:
結論:
當把過濾條件寫在where上,只會讓符合篩選條件的資料顯示。
鳴謝與參考:
https://blog.csdn.net/qq_20641565/article/details/52950087
https://blog.csdn.net/wangwangstone/article/details/112550095