1. 程式人生 > >SQL使用總結-like,MAX,MIN

SQL使用總結-like,MAX,MIN

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. 索引不容許使用MaxMin

直接對索引采用采用MAXmin關鍵字,將執行遍歷操作,索引毫無價值。

錯誤寫法:

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