Heim  >  Fragen und Antworten  >  Hauptteil

mysql中longtext存在大量数据时,会导致查询很慢?

一个表,1.5w条数据,字段: id,name,content,last_update_time
id,自定义主键
name,varchar类型
content是longtext类型,
last_update_time为datetime类型,不为空

content当中是文本和代码等,平均长度在20k+。

case1:
select id, name from t order by last_update_time limit 10000, 10

当content当中有大量的文本时,case1的效率极慢。

及时给 last_update_time 加上btree索引, 效率有提升,但是依然慢

把content一列删掉,效率很高。毫秒级别。

使用explain:
有content时结果:

mysql> explain select id, name, last_update_time from t order by last_update_time desc limit 11120, 11;
+----+-------------+-----------+-------+---------------+----------------------+---------+------+-------+-------+
| id | select_type | table     | type  | possible_keys | key                  | key_len | ref  | rows  | Extra |
+----+-------------+-----------+-------+---------------+----------------------+---------+------+-------+-------+
|  1 | SIMPLE      | t | index | NULL          | idx_last_update_time | 8       | NULL | 11131 | NULL  |
+----+-------------+-----------+-------+---------------+----------------------+---------+------+-------+-------+

无content列的结果:

+----+-------------+----------------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table          | type | possible_keys | key  | key_len | ref  | rows  | Extra          |
+----+-------------+----------------+------+---------------+------+---------+------+-------+----------------+
|  1 | SIMPLE      | t2 | ALL  | NULL          | NULL | NULL    | NULL | 15544 | Using filesort |
+----+-------------+----------------+------+---------------+------+---------+------+-------+----------------+
1 row in set (0.00 sec)

请大神请教,是什么问题?该怎么优化?

PHPzPHPz2741 Tage vor2211

Antworte allen(3)Ich werde antworten

  • ringa_lee

    ringa_lee2017-04-17 16:02:16

    无content的时候,查询走的是idx_last_update_time,我猜测这个索引中包含了id,name字段,因此仅通过索引就可以获取到所需的数据,因此速度很快。
    有content的时候,因为有limit 10000的语句,且无法从索引中获取content字段的内容,因此采用的全表扫描的方法。
    建议改写sql语句,让数据库的执行计划更充分使用索引,假设id是主键:

    select id, name, content 
    from t
    where id in (
      select id
      from t
      order by last_update_time limit 10000, 10
    )

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-04-17 16:02:16

    content当中是文本和代码等,平均长度在20k+。

    这种应该建立全文索引(FUNLLTEXT INDEX)吧。简单的索引不适合这种超长文本的字段。

    Antwort
    0
  • PHP中文网

    PHP中文网2017-04-17 16:02:16

    我觉得,主要跟你的分页查询的方式有关,limit 10000,10 这个意思是扫描满足条件的10010条数据,扔掉前面的10000行,返回最后的10行,在加上你的表中有个,非常大的字段,这样必然增加数据库查询的i/o时间,
    查询优化你可以参照 @邢爱明 的
    SELECT id,title,content FROM items WHERE id IN (SELECT id FROM items ORDER BY last_update_time limit 10000, 10);
    还有一种优化方式:你可以记录最后的last_update_time 每次最后的值。然后查询可以这样写:
    SELECT * FROM items WHERE last_update_time > "最后记录的值" order by last_update_time limit 0,10;

    这两种方式你可以执行看看那个效率高,希望对你有帮助。。

    Antwort
    0
  • StornierenAntwort