简体   繁体   English

慢的SQL执行

[英]Slow Sql Execution

I have a table that contains at least 60,000 rows. 我有一个包含至少60,000行的表。 My query is just basic, and it is something like this: 我的查询只是基本查询,它是这样的:

SELECT `table`.name, `table`.age, `table`.points
                              FROM table
                              GROUP BY name, age
                              ORDER BY date
                              DESC
                              LIMIT 12

The result is like (12 total, Query took 1.2211 sec) , sometimes it even takes 2 seconds to just return 12 rows. 结果是(总共12条,查询用了1.2211秒) ,有时甚至需要2秒才返回12行。

What should be done to make my query faster? 如何使我的查询更快?

EXPLAIN QUERY: 说明查询:

id | select_type | table |  type  | possible_keys |  key  |  key_len  |  ref  | rows  | Extra |
1       Extra      table    ALL        NULL          NULL    NULL        NULL   65704   Using temporary; Using filesort

This is too long for a comment. 这个评论太长了。 An index on date will help,without it it is forced to do a table scan. 日期索引会有所帮助,如果没有索引,它将被迫进行表扫描。 Also what is the cardinality of name,that is the number of distinct names divided on the number of rows ?In case it is low you can create a table with those distinct names and JOIN on that,aiming for a loose index scan. 另外,名称的基数是什么,即不同名称的数量除以行数?如果它很低,则可以创建一个具有这些不同名称的表,并在其上进行JOIN,以进行松散的索引扫描。 For beginning try a composed index : 首先尝试一个组合索引:

 ALTER TABLE t1 ADD KEY indexName (name,age,date)

For more details put an EXPLAIN before your query and edit your question with the results. 有关详细信息把一个EXPLAIN查询之前的结果编辑你的问题。

You might want to create indexes in your SQL Database. 您可能要在SQL数据库中创建索引。 If you're using MYSQL you can create them like this 如果您使用的是MYSQL,则可以这样创建它们

ALTER TABLE TABLE_NAME ADD INDEX (COLUMN_NAME);

For your case it would be like: 对于您的情况,它将是:

ALTER TABLE `table` ADD INDEX (name);
ALTER TABLE `table` ADD INDEX (age);
ALTER TABLE `table` ADD INDEX (points);

You might also want to have a look at this question 您可能还想看看这个问题

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

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