>백엔드 개발 >PHP 튜토리얼 >Select多行SQL语句慢查询优化

Select多行SQL语句慢查询优化

WBOY
WBOY원래의
2016-06-06 20:49:151239검색

环境:MySQL5.5 InnoDB表 post ,主键为 id

需求非常简单,根据id返回 post.name ,需要一次返回指定的多个,所以使用了where id in

<code>select `name` from `post` where `id` in(2142324,2106574,2106564,2075699,2065402,2050790,2038346,2038345,2035588,2031765,2022035,2022034,2020745,2020737,2020718,1987558,1970241,1962232,1911342,1891481,1889641,1877438,1877434,1867217,1866057,1866013,1847315);
</code>

Explain结果:

<code>+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | post  | range | PRIMARY       | PRIMARY | 4       | NULL |   27 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
</code>

现在这句SQL一小时产生几千条慢查询记录,我直接在console执行每次也需要7,8秒

能怎么优化呢?

回复内容:

环境:MySQL5.5 InnoDB表 post ,主键为 id

需求非常简单,根据id返回 post.name ,需要一次返回指定的多个,所以使用了where id in

<code>select `name` from `post` where `id` in(2142324,2106574,2106564,2075699,2065402,2050790,2038346,2038345,2035588,2031765,2022035,2022034,2020745,2020737,2020718,1987558,1970241,1962232,1911342,1891481,1889641,1877438,1877434,1867217,1866057,1866013,1847315);
</code>

Explain结果:

<code>+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | post  | range | PRIMARY       | PRIMARY | 4       | NULL |   27 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+------+-------------+
</code>

现在这句SQL一小时产生几千条慢查询记录,我直接在console执行每次也需要7,8秒

能怎么优化呢?

从纯sql的角度看是没问题的,走了索引,rows值也不大,如果速度很慢,可以从3个方面看 1:innodb参数是否已经优化,比如innodbbufferpoor_size等 2:qcache命中率。根据你上诉问题,一小时该语句产生几千条慢查询,命中率明显不高,是否该表写入频率过高导致qcache失效,是否考虑读写分离 3:数据量大的话考虑分区,或者水平分表

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.