資料庫 子查詢《mysql子查詢的弱點》

2021-07-26 22:53:58 字數 947 閱讀 4322

mysql的子查詢的優化不是很友好,一直有受業界批評比較多.  

關於mysql的查詢有兩個知識點:

1.第乙個為mysql在處理所有的查詢的時候都強行轉換為聯接來執行,將每個查詢包括多表中關聯匹配,關聯

子查詢,union,甚至單錶的的查詢都處理為聯接,接著mysql執行聯接,把每個聯接在處理為乙個巢狀迴圈

(oracle-nest-loop);

2.在mysql在處理子查詢的時候,會將將子查詢改寫,通常情況下,我們希望由內到外,先完成子查詢的結果,

然後在用子查詢來驅動外查詢的表,完成查詢。例如:select * from test where test_id in

(select fk_test_id from sub_test where group_id=10)通常我們會想到該sql的執行順序為:

sub_test表中根據group_id取得fk_test_id(2,3,4,5,6),然後在到test中,帶入test_id=2,3,4,5,6

取得查詢資料,但是實際mysql的處理方式為:select * from test where exists (select * from

sub_test where group_id=10 and sub_test.test_id=test.id)。mysql將會掃瞄test中的所有資料,

每條資料將會傳到子查詢中與sub_test關聯,子查詢不能首先被執行,如果test表很大的話,那麼效能上將會

出現問題;

這時候就需要改寫查詢了:select t1.* from test t1,(select fk_test_id from sub_test where

group_id=10) t2 where t1.test_id=t2.fk_test_id ;

參考:

資料庫子查詢

概念 當乙個查詢是另乙個查詢的條件時,這個查詢稱之為子查詢 內層查詢 主要有以下三種表現形式 1.select 列 from 子查詢 2.select 列 from 表 where 列 比較運算子 子查詢 3.select 列 from 表 left join 子查詢 left join 子查詢 字...

MySQL資料庫 使用子查詢

selcet語句是sql的查詢。迄今為止我們所看到的所有selcet都是簡單查詢,即從單個資料庫表中檢索資料的單條語句。sql還允許建立子查詢,就是巢狀在其他查詢內的查詢!part 1 使用子查詢進行過濾 select coder.code id from coder where id in sel...

mysql資料庫 子查詢(9)

mysql資料庫 子查詢 把乙個查詢巢狀在另乙個查詢當中的方式,返回結果是根據兩個查詢共同作用的結果。子查詢語法格式 select filed,filed from tbname where 例如 select frome tbname in select frome tbname not in s...