簡體   English   中英

需要幫助提高 SQL 查詢的性能

[英]Need help in improving performance of SQL query

看看我制作的這個 sqlfiddle 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

您尚未在任何列上創建任何索引。 在編寫大量查詢之前,請閱讀線性搜索和二分搜索。

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

首先,您可以為以下列( idtable1_id, created_reason , created_at timestamp, updated_at timestamp, deleted_at` 時間戳)創建聚集索引;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM