hive in not in 改寫
in的改寫
考慮以下 SQL 查詢語句:
SELECT a.key, a.value FROM a
WHERE a.key in (SELECT b.key FROM B);
可以改為:
SELECT a.key, a.value
FROM a LEFT OUTER JOIN b ON (a.key = b.key)
WHERE b.key <> NULL;
一個更高效的實現是利用 left semi join 改寫為:
SELECT a.key, a.val
FROM a LEFT SEMI JOIN b on (a.key = b.key);
not in 的改寫
可以改用 not exists:
eg1.
select * from A
where not exists
(select * from B
where A.uid=B.uid and A.goods=B.goods);
select dw.apply_id
from d_extra.dw_order_dkw dw
where dw.topicdate = '2017-08-01'
and not exists(
select rpt.apply_id
from report.report_dkw_apply_detail rpt
where rpt.topicdate = '2017-08-01'
and dw.apply_id = rpt.apply_id
)
或者用join,然後選擇沒連線上的:
select t1.a, t2.b
from table1 t1
left join table2 t2 on (t1.a = t2.a and t1.b = t2.b)
where t2.a is null
update:
據說Hive對子查詢的支援很有限。它只允許子查詢出現在SELECT語句的FROM子句中。
如果發現Hive不支援你寫的子查詢,可以看看能不能把它寫成連線操作。例如,一個IN子查詢可以寫成一個半連線或連線。
查hive官網:hive在0.13版本以後開始支援更多的子查詢,如in ,not in的子查詢。如果我們用的hive不支援如in,exists,not in等子查詢,很可能是0.13版本之前的舊版本。
此外,需要注意not in 和 not exists 不完全相同的:
t1
1 2
1 3
t2
1 2
1 null
select * from #t1 where c2 not in(select c2 from #t2); -->執行結果:無
select * from #t1 where not exists(select 1 from #t2 where #t2.c2=#t1.c2) -->執行結果:1 3