首頁 >後端開發 >php教程 >Select多行SQL语句慢查询优化

Select多行SQL语句慢查询优化

WBOY
WBOY原創
2016-06-06 20:49:151228瀏覽

环境: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