考勤記錄cardtime表id,userid,logtime 三个字段,大概350萬條記錄,php+mysql 查詢時很慢,如果查其中一個人的每月記錄,差不多要10S左右,建了索引查詢還是很慢,有沒其它辦法提高查詢速度,查詢條件是select * from cardtime where userid="13155" and logtime like '%2009-06%',這樣查時會掃描整個表所以很慢,有沒其它辦法!
调试欢乐多
后面的查询条件,也可以改一下,改成具体查询。 用 MONTH,YEAR 或者 ..FORMAT 等转化一下
logtime like '%2009-06%'语句,改成
date_format(logtime, '%Y-%m') = '2009-06'
在后面加上limit子句
select * from cardtime where userid="13155" and date_format(logtime, '%Y-%m') = '2009-06' limit 0, 30
如果用也不要 like '%xxx%'
儘量不要用like語句
但是在下结论之前,先察看下执行效果后再下定论EXPLAIN select * from cardtime where userid="13155" and logtime like '%2009-06%'
就拿这条sql来说,主要问题出在like子句,如果logtime字段是char类型,可以考虑给logtime的的前7位创建索引
使用语句。
select * from cardtime where userid="13155" and logtime like '2009-06%'如果搜索量频繁,可以考虑建立组合索引(userid,logtime);
还是先explian下吧。看看索引使用情况
EXPLAIN select * from cardtime where userid="13155" and logtime like '%2009-06%' 這樣查詢並沒有返回查詢結果,只是查詢索引信息!如下:id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE cardlogtime ref search_userid_logtime search_userid_logtime 102 const 111 Using where
alter table cardlogtime add index search_userid_logtime(userid,logtime)
10楼的正解
where userid="13155"
and logtime between '2009-06-01' and '2009-06-30 23:59:59'然后建立复合索引 (userid ,logtime)