浅谈mysql之索引

说是浅谈,其实就是东拉西扯点儿mysql优化方面的东西罢了。

下面来共同学习一下:

1 ,当select时用到like模糊查询,如like  '%name' ,mysql是不走索引的,而当使用like  'name%' ,即把‘%’放到要查询内容的后面就可以用到索引。

2 ,查询条件中要是有or,则不会走索引。

3 ,对于多列索引,若用的不是最左侧的索引,整个查询也就不走索引(最左原则)。

4 ,如果查询条件中的列是字符串,则要用' '引号引上,否则不走索引。如 select name from table_name where name = xiaoming ;这句sql就不会走索引。

5 ,查看索引的使用情况:

show status like 'Handler_read';

其中,

handle_read_key          -- 值越高,sql走索引的次数就越高,代码就越高效
handle_read_rnd_next     -- 值越高,sql没走索引的次数就越高,代码就越低效

6 ,主键要尽可能选择较短的数据类型,这样可以有效的减少磁盘占用,提高索引的缓存效果。

7 , 写完sql语句后多explain,减少慢sql。

8 , 通过

扫描二维码关注公众号,回复: 2854481 查看本文章
set slow_query_log = ON -- 开启慢查询日志并隔时间删除旧日志

使用

mysqldumpslow  localhost-slow.log

查看和分析慢查询。

9 , 经常通过

optimize table table_name -- 对MyISAM的优化

优化MyISAM引擎的表,减少磁盘占用。

10 , 慢sql的详细检查工具profiling,这是在mysql 5.0.37版本后出现的,非常便捷。具体用法如下:

mysql> show variables like '%profiling%';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| have_profiling         | YES   |
| profiling              | OFF   |
| profiling_history_size | 15    |
+------------------------+-------+
3 rows in set (0.00 sec)

mysql> set profiling = 1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> show variables like '%profiling%';
+------------------------+-------+
| Variable_name          | Value |
+------------------------+-------+
| have_profiling         | YES   |
| profiling              | ON    |
| profiling_history_size | 15    |
+------------------------+-------+
3 rows in set (0.00 sec)

首先打开profiling,置为1或ON皆可。

然后输入sql语句,例如:select * from test;

之后,

show profiles

接着看刚才的sql语句对应于query 几, 如:query 6

那么,我们就要查看query 6 的执行情况了,用

show profile for query 6

 这样,我们就可以看到具体是什么原因导致sql变慢的。

比如,我这里查出来是这样的:

mysql> show profile for query 43;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000136 |
| checking permissions | 0.000009 |
| Opening tables       | 0.000018 |
| init                 | 0.000022 |
| System lock          | 0.000010 |
| optimizing           | 0.000007 |
| statistics           | 0.000103 |
| preparing            | 0.000027 |
| Sorting result       | 0.000003 |
| executing            | 0.000002 |
| Sending data         | 0.000079 |
| end                  | 0.000004 |
| query end            | 0.000005 |
| closing tables       | 0.000006 |
| freeing items        | 0.000054 |
| cleaning up          | 0.000017 |
+----------------------+----------+
16 rows in set, 1 warning (0.00 sec)

猜你喜欢

转载自blog.csdn.net/qq_40795214/article/details/81811888