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

问题描述:

看看这个sqlfiddle我做了http://sqlfiddle.com/#!9/4b903/2/0。这是我的数据库的简化版本。我在历史上有100万条记录,问题是查询似乎太慢。有时需要一分钟才能得到结果。我在这个SQL的东西不太好。我想有一些列需要索引,但我不知道那些是什么。需要帮助来提高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 
 
+0

创建索引。 https://dev.mysql.com/doc/refman/5.6/en/optimization-indexes.html – hjpotter92

+0

顺便说一句钱通常是DECIMAL,而不是FLOAT – Strawberry

+0

另外,您正在使用相关的子查询。一个非编码的几乎总是更快。 – Strawberry

可以为以下几列 创建聚簇索引的第一件事情(idtable1_id, created_reason , created_at timestamp,的updated_at timestamp, deleted_at`时间戳);

然后,而不是子查询将这些结果集放入临时表,并尝试加入该临时表和主表。

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

添加索引到Table

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;