mysql技巧

1,使用強制索引

某些字段沒有加索引,但需要通過字段查詢,可以使用強制索引

如下,dateline字段未建立索引,對dateline字段使用強制索引

select id from A force(dateline) where dateline>100000;


2,按指定字段自定義列表排序

order by field('id',5,3,7,1)

select * from A where id in(1,7,3,5) order by field('id',5,,3,7,1)


3,find_in_set(str,strlist);

str要查詢的字符串

strlist字段名 參數以“,”分割,如(1,2,6,8)

查詢字段strlist中包含str的結果

查詢area中包含“1”這個參數的記錄

select * from A where find_in_set('1',area);


find_in_set和like

like是模糊匹配,字符串沒有分隔符,find_in_set是精確匹配,字段值以‘,’分割


4,like

"%aa%"這樣是用不到索引的

“aa%”這樣可以用到索引


大數據下如何使用like???

直接使用“%keyword%”,會導致全表掃描且效率非常低

這時我們可以嘗試使用locate('substr',str,pos)

返回substr在str中第一次出現的位置,如果substr在str中不存在,返回值爲0.存在返回第一次出現的位置,

如果有pos參數,則返回substr在str第pos個位置後第一次出現的位置,不存在則返回0

select name from A where locate('keyword',name)>0


數據特別大可以考慮全文搜索引擎

阿里雲OpenSearch

Solr

Elasticsearch


5,mysql隨機返回部分結果

order by rand()

隨機查詢一條數據

select * from A order by rand() limit 1;

效率非常低,order by 和rand()連用,會多次掃描


select * from A where id>=(select floor(rand()*(select max(id) from A))) limit 1;

先找出一個小於max(id)的隨機值


select * from A where id>=(select floor(rand()*((select max(id) from A) - (select min(id) from A)))++(select min(id) from A)) limit 1

select floor(rand()*((select max(id) from A) - (select min(id) from A)))++(select min(id) from A)獲取max(id)和min(id)之間的隨機數


隨機取多條數據

如果按上面的方法獲取的數據是連續的

select * from A as a1 join (select round(rand()*((select max(id) from A) - (select min(id) from A))+(select min(id) from A)) as id from A limit 50) as a2 on t1.id=t2.id order by t1.id limit 5;

select round(rand()*((select max(id) from A) - (select min(id) from A))+(select min(id) from A)) as id from A limit 50

這樣回獲取50個隨機數字 然後on t1.id=t2.id獲取A中的5條數據


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章