建立索引应该尽量少用VARCHAR、TEXT、BLOB类型,如果一定要用可以只索引开头指定长度的字符。 如; create index idx_key on table_name(key(5)) 只索引table_name表中key字段的前5个字符。 使用过长的索引,不但浪费磁盘空间,而且使磁盘I/O减慢, 使查询、更新,插入数据变得比不加索引更慢。
我测试的代码: select * from t_test where a=0 and b=0 group by key order by time desc limit 1,100意思大家能看懂吗?字段a和b的值(0或1);key varchar(255);id是主键;time时间。 我在key上加了索引create index index_key on t_test (key);explain的结果: +---------+------+---------------+------+---------+------+------+--------------- ------------------------------+ | table | type | possible_keys | key | key_len | ref | rows | Extra | +---------+------+---------------+------+---------+------+------+--------------- ------------------------------+ | t_s | ALL | NULL | NULL | NULL | NULL | 300 | where used; Us ing temporary; Using filesort | +---------+------+---------------+------+---------+------+------+--------------- ------------------------------+这样每次都是全表查询,现在我随便放了300条,如果记录一多的话,难以想象,有什么好的办法优化吗?
to johnpanq(飞花逐月) 我现在碰到的可能就是你说的那种情况,字段太长了,用了反而效率没有提高。
如;
create index idx_key on table_name(key(5))
只索引table_name表中key字段的前5个字符。
使用过长的索引,不但浪费磁盘空间,而且使磁盘I/O减慢,
使查询、更新,插入数据变得比不加索引更慢。
select * from t_test where a=0 and b=0 group by key order by time desc limit 1,100意思大家能看懂吗?字段a和b的值(0或1);key varchar(255);id是主键;time时间。
我在key上加了索引create index index_key on t_test (key);explain的结果:
+---------+------+---------------+------+---------+------+------+---------------
------------------------------+
| table | type | possible_keys | key | key_len | ref | rows | Extra
|
+---------+------+---------------+------+---------+------+------+---------------
------------------------------+
| t_s | ALL | NULL | NULL | NULL | NULL | 300 | where used; Us
ing temporary; Using filesort |
+---------+------+---------------+------+---------+------+------+---------------
------------------------------+这样每次都是全表查询,现在我随便放了300条,如果记录一多的话,难以想象,有什么好的办法优化吗?
我现在碰到的可能就是你说的那种情况,字段太长了,用了反而效率没有提高。