oracle inner join 的效率 [轉]
我做了個試驗,比如有如下語句 select * from table1 t1 inner join table2 t2 on t1.XX=t2.XX inner join table3 t3 on t2.XX =t3.XX ,
看他的執行計劃,XX這個列是有索引的,但他的第一步是對table3進行全表掃描,然後再用索引去掃描table2, 也就是說,inner join的執行順序是從後往前,先把table3的資料提取出來,再通過條件去找table2,所以在寫SQL語句的時候,最好把能排除大量資料的條件放到最後
將 上句改為:select * from table1 t1 inner join table2 t2 on t1.XX=t2.XX inner join table3 t3 on t2.XX =t3.XX where t3.XX between A AND B,這樣效率就上去了,不用在每個inner join後面都加條件,另外 每次inner join 一個表,就會先對這個表進行全表掃描,然後他們再聯表,如果多個表,或表的行數很多,他們的效率很低,消耗幾乎是每個表的行數相乘,所以有條件儘量在inner join的時候就用,別用在最後,
將上句改為:select * from (select * from table1 where XX between A AND B ) t1 inner join (select * from table2 where XX between A AND B)t2 on t1.XX=t2.XX inner join(select * from table3 where XX between A AND B)t3 on t2.XX =t3.XX 這樣的執行效率會高很多