2016-04-25 81 views
0

看看這個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

回答

0

可以爲以下幾列 創建聚簇索引的第一件事情(idtable1_id, created_reason , created_at timestamp,的updated_at timestamp, deleted_at`時間戳);

然後,而不是子查詢將這些結果集放入臨時表,並嘗試加入該臨時表和主表。

1

您尚未在任何列上創建任何索引。請在編寫大量查詢之前閱讀關於線性和二進制搜索的內容。

添加索引到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;