3 回答

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
mysql百萬數(shù)據(jù)查詢用exists 代替 in 是一個(gè)好的選擇:
select num from a where num in(select num from b)
用下面的語句替換:
select num from a where exists(select 1 from b where num=a.num)
SQL查詢語句優(yōu)化方法:
1、應(yīng)盡量避免在 where 子句中使用!=或<>操作符,否則將引擎放棄使用索引而進(jìn)行全表掃描。
2、對(duì)查詢進(jìn)行優(yōu)化,應(yīng)盡量避免全表掃描,首先應(yīng)考慮在 where 及 order by 涉及的列上建立索引。
3、應(yīng)盡量避免在 where 子句中對(duì)字段進(jìn)行 null 值判斷,否則將導(dǎo)致引擎放棄使用索引而進(jìn)行全表掃描,如:
select id from t where num is null
可以在num上設(shè)置默認(rèn)值0,確保表中num列沒有null值,然后這樣查詢:
select id from t where num=0
4、盡量避免在 where 子句中使用 or 來連接條件,否則將導(dǎo)致引擎放棄使用索引而進(jìn)行全表掃描,如:
select id from t where num=10 or num=20
可以這樣查詢:
select id from t where num=10
union all
select id from t where num=20
5、下面的查詢也將導(dǎo)致全表掃描:(不能前置百分號(hào))
select id from t where name like ‘%c%’
若要提高效率,可以考慮全文檢索。

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
這個(gè)主鍵ID其實(shí)已經(jīng)是有建立了索引的了,而在IN查詢當(dāng)中并沒有用到而已,其實(shí)你可以試試IN里的id少些時(shí),是會(huì)用到索引的,但當(dāng)IN里的id占據(jù)全表的大部分?jǐn)?shù)據(jù)量時(shí),mysql采用的時(shí)全表掃描。在這個(gè)時(shí)候可以考慮:1.split返回臨時(shí)表進(jìn)行表連接,2.使用緩存遍歷
添加回答
舉報(bào)