SQL使用總結-like,MAX,MIN
阿新 • • 發佈:2017-06-17
des 字符串操作 time pla 技術分享 order by -1 add and
1. 時間索引不容許使用like
對時間索引適應like,會時間索引變成字符串操作,成為遍歷動作,失去索引價值。
錯誤寫法:
EXPLAIN SELECT AVG(data_value) AS avg_value FROM `host_monitor` WHERE host_ip= ‘192.168.106.11‘ AND data_type=3 AND add_time LIKE ‘2017-05-19 01%‘;
正確寫法:
EXPLAIN SELECT AVG(data_value) AS avg_value FROM `host_monitor` WHERE host_ip= ‘192.168.106.11‘ AND data_type=4 AND add_time >= ‘2017-05-19 01:00:00‘ AND add_time<=‘2017-05-19 01:59:59‘;
2. 索引不容許使用Max,Min
直接對索引采用采用MAX,min關鍵字,將執行遍歷操作,索引毫無價值。
錯誤寫法:
EXPLAIN SELECT MAX(add_time) FROM host_monitor WHERE host_ip = ‘192.168.106.11‘ AND data_type = 6
正確寫法:
EXPLAIN SELECT add_time FROM host_monitor WHERE host_ip = ‘192.168.106.11‘ AND data_type = 6 ORDER BY add_time DESC LIMIT 1
SQL使用總結-like,MAX,MIN