简体   繁体   English

MySQL中的快速页面检索,索引用法?

[英]Fast page retrieval in MySQL, index usage?

I would like to speed a MySQL query that basically retrieve a page of data following the pattern below 我想加快一个MySQL查询,它基本上按照下面的模式检索一页数据

select
 my_field_A,
 my_field_B
where
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')

The field time_id is an MySQL index, yet, the query behaves as if the entire database was read at each query (retrieving a couple of lines being already quite slow). 字段time_id是一个MySQL索引,但是,查询的行为就像在每个查询中读取整个数据库一样(检索几行已经非常慢)。 I not an expert in MySQL. 我不是MySQL的专家。 Can someone guess what I am doing wrong? 谁能猜出我做错了什么?

Make sure you have an index (B-tree) on time_id, this should be efficient for range queries. 确保在time_id上​​有一个索引(B树),这应该对范围查询有效。 Also make sure that time_id is in the appropriate time format. 还要确保time_id采用适当的时间格式。

If you really want to understand what mysql is doing you can add the keyword 'explain' infront of the query and run it in your mysql client. 如果你真的想了解mysql正在做什么,你可以在查询的前面添加关键字'explain'并在你的mysql客户端中运行它。 This will show some information about what mysql is doing and what kind of scans are performed. 这将显示有关mysql正在执行的操作以及执行的扫描类型的一些信息。

http://dev.mysql.com/doc/refman/5.0/en/using-explain.html http://dev.mysql.com/doc/refman/5.0/en/using-explain.html

As there are probably lots of time_id 's falling under these criteria, MySQL may think that the full table scan is better. 由于可能有很多time_id属于这些标准, MySQL可能会认为全表扫描更好。

Try forcing the index: 尝试强制索引:

SELECT
 my_field_A,
 my_field_B
FROM mytable FORCE INDEX (index_name_on_time_id)
WHERE
 time_id >= UNIX_TIMESTAMP('1901-01-01  00:00:00') AND
 time_id < UNIX_TIMESTAMP('2009-01-16  00:00:00')

Do you need the lower range? 你需要更低的范围吗? Are there any entries earlier than 1901? 有没有比1901年更早的参赛作品? How is the time_id column generated? time_id列是如何生成的? If the time_id is always greater with each new entry being added into DB, you may want to consider finding ID with closest entry to 2009-01-16 and then select by ID 如果每个新条目都添加到DB中时time_id总是更大,您可能需要考虑查找最接近2009-01-16条目的ID,然后按ID选择

select my_field_A, my_field_B
FROM
  mytable
WHERE
  id <= ?

If that is not the case, try checking out partitioning in available from MySQL 5.1 and break down the table by years, that should increase speed dramatically. 如果不是这种情况,请尝试检查MySQL 5.1中可用的分区并按年分解表,这应该会显着提高速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM