需要帮助来提高SQL查询的性能

时间:2016-04-25 03:00:18

标签: mysql

看看我制作的这个方形小册子http://sqlfiddle.com/#!9/4b903/2/0。这是我的数据库的简化版本。我现在在历史上有一百万条记录,问题是查询看起来太慢了。有时需要一分钟才能得到结果。我在这个sql中并不是很好。我想有一些我需要索引的列,但我不确定那些是什么。

更新

我试着解释sql


id | select_type        | table | type  | possible_keys                                       | key               | key_len | ref          | rows  | Extra
1  | PRIMARY            | t1    | range | created_reason,created_reason_2                     | created_reason_2  | 6       | NULL         | 91136 | Using where; Using temporary; Using filesort
2  | DEPENDENT SUBQUERY | t2    | ref   | history_table1_id_foreign,table1_id,table1_id_2     | table1_id_2       | 4       | t1.table1_id | 11    | Using where; Using index; Using filesort

2 个答案:

答案 0 :(得分:1)

您尚未在任何列上创建任何索引。在编写大量查询之前,请阅读线性和二进制搜索。

向table1添加索引

alter table `test_delete`.`table1` 
add index `idx_created_at` (`created_at` asc),
add index `idx_price` (`price` asc);

将索引添加到历史记录

alter table `test_delete`.`history` 
add index `idx_history_created_at` (`created_at` asc),
add index `idx_history_price` (`price` asc),
add index `idx_table1_id` (`table1_id` asc);

一个小小的改变 - 赢得了很大的影响

select t1.* from history t1 where t1.created_at >= '2016-03-13 00:00:00'
and t1.created_reason = 'Scraped'
and t1.price not in (-1, (
         select t2.price
           from history t2
          where t2.table1_id = t1.table1_id
            and t2.created_at  < t1.created_at
            and t2.created_at  > t1.created_at + interval -30 day
            and t2.price > -1
          order by t2.created_at desc
          limit 1
       ))
group by t1.table1_id;

答案 1 :(得分:0)

首先,您可以为以下列创建聚簇索引 (import Ember from 'ember'; export default Ember.Route.extend({ model(params) { console.log(params); //20160422-tutorial let post = this.store.queryRecord('post', {slug: params.slug}, { reload: true }); console.log(post); //shows all 7 records here and in the ember inspector. return post; } }); id created_reason table1_id, created_at , updated_at timestamp, deleted_at` timestamp);

然后代替子查询将这些结果集放入临时表并尝试连接该临时表和主表。

相关问题