生活随笔
收集整理的這篇文章主要介紹了
MySQL 搜索指定时间范围数据, 时间字段有索引但是还是很费时
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題分析
數據庫版本:5.6.38查詢時使用時間類型,在status、closed、playback_state字段上都有索引幾種查詢語句 explain (select count(*) ? ? ? ? from session ? ? ? ? where status = 2 ? ? ? ? ? and playback_state = 1 ? ? ? ? ? and closed > '2018/10/17' ? ? ? ? ? and closed < '2018-10-18'); explain (select count(*) ? ? ? ? from session ? ? ? ? where status = 2 ? ? ? ? ? and playback_state = 1 ? ? ? ? ? and closed like '2018-10-17%'); explain (select count(*) ? ? ? ? from session ? ? ? ? where status = 2 ? ? ? ? ? and playback_state = 1 ? ? ? ? ? and closed > 1539705600 ? ? ? ? ? and closed < 1539792000); explain (select count(*) ? ? ? ? from session ? ? ? ? where status = 2 ? ? ? ? ? and playback_state = 1 ? ? ? ? ? and closed > unix_timestamp('2018/10/17') ? ? ? ? ? and closed < unix_timestamp('2018-10-18')); 查詢情況:第一種情況使用closed的索引,查詢速度很快. 其他使用playback_state,因為playback_state相同的數據有很多,因此除第一種情況外,其他情況都很糟糕。 mysql查詢時,不管有多少個單個索引或聯合索引,永遠只使用一個索引。
具體使用哪個索引進行查詢,由mysql進行選擇,會選擇一個它認為最合適的一個字段。在以上情況中,其選擇了playback_state,而非closed。
當語句執行太長時間,使用explain看一下查詢情況,mysql是否使用了正確的索引。在有索引的字段上使用函數是會把索引去掉的。可以使用use index強制mysql使用固定索引可以考慮使用聯合索引(開發不能隨意改動數據庫的表結構)
轉載于:https://www.cnblogs.com/Zereker/p/11396623.html
總結
以上是生活随笔為你收集整理的MySQL 搜索指定时间范围数据, 时间字段有索引但是还是很费时的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。