看到很多網友在說join的時候,where一定要在on的條件之前,這樣可以起到優化左右,比如有同學這樣說(如下截圖),其實不然,對此我做了實驗
爲驗證此結論我選擇了一個大表進行數據驗證,進行了sparksql查詢
sql1是這樣的,where在on前面
select t1.c0
, t1.c1
, t1.c2
, t1.c3
, t1.c4
, t1.c5
, t1.c6
, t1.c7
, t1.c8
, t1.c9
, t1.c10
, t1.c11
, t1.c12
, t1.c13
, t1.c14
, t1.c15
, t1.c16
, t1.c17
, t1.c18
, t1.c19
, t1.c20 from
(SELECT
c0
, c1
, c3
, c4
, c5
, c6
, c7
, c8
, c9
, c10
, c11
, c12
, c13
, c14
, c15
, c16
, c17
, c18
, c19
, c20
, c21
FROM d_dt.table_new where event_date= '2020-05-08') t1
LEFT JOIN
(
SELECT c10,c21 FROM d_dt.table_active WHERE event_date='2020-05-09'
) t2 on (t1.c10 = t2.c10 and t1.c20 = t2.c20)
where t2.10 is null;
sql2是這樣的,where在on後面
SELECT
c0
, c1
, c3
, c4
, c5
, c6
, c7
, c8
, c9
, c10
, c11
, c12
, c13
, c14
, c15
, c16
, c17
, c18
, c19
, c20
, c21
FROM d_dt.table_new t1
LEFT JOIN
(
SELECT c10,c21 FROM d_dt.table_active WHERE event_date='2020-05-09'
) t2 on (t1.c10 = t2.c10 and t1.c20 = t2.c20)
where t1.event_date= '2020-05-08')
and t2.10 is null;
結論,執行時間並沒有明顯差異,在 spark ui 看dag執行計劃完全一樣,不論where是在on前面還是後面,前面兩步都是按指定的event_date分區去掃描數據,所以在效率角度分析where 在on前面還是on後面沒有明顯的差異
歡迎有不同意見的同學在評論區進行討論補充,共同學習共同成長