1. 程式人生 > >資料庫SQL查詢效率in、exists、left join on、right join on 適用場景與比較

資料庫SQL查詢效率in、exists、left join on、right join on 適用場景與比較

in 與 join例

select t1.id,sum(t1.num) from (select * from t2 where num =2) as t3 LEFT JOIN t1 on t3.id=t1.id GROUP BY t1.id; join 時間: 0.005s 0.009s

select id,sum(num) from t1 where id in (select id from t2 where num =2) group by id; in 時間: 0.013s 0.017s

--------------------- 本文來自 shooke 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/shooke/article/details/80077750?utm_source=copy

in和exists(摘錄自百度)
in 是把外表和內表作hash 連線,而exists是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。

如果兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in:
例如:表A(小表),表B(大表)
1:select * from A where cc in (select cc from B)效率低,用到了A表上cc列的索引;
   select * from A where exists(select cc from B where cc=A.cc)效率高,用到了B表上cc列的索引。
相反的2:select * from B where cc in (select cc from A)效率高,用到了B表上cc列的索引;
        select * from B where exists(select cc from A where cc=B.cc)效率低,用到了A表上cc列的索引。
not in 和not exists如果查詢語句使用了not in 那麼內外表都進行全表掃描,沒有用到索引;
而not extsts 的子查詢依然能用到表上的索引。所以無論那個表大,用not exists都比not in要快。

in 與 =的區別
select name from student where name in ('zhang','wang','li','zhao');與
select name from student where name='zhang' or name='li' or
name='wang' or name='zhao'
的結果是相同的。
left\right join是外部連線,inner join是內連線
外部連線有主表與從表,主表在left中是左側表,right中是右側表,主表資料會全部顯示,從表資料則只顯示關聯部分匹配的資料,無匹配的資料用null補全
內連線則只顯示兩表關聯條件匹配的資料
注:所謂關聯條件即是指on的條件

where 與 inner join是一樣的,但是多用inner join