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

Mysql 需要帮助提高SQL查询的性能吗,mysql,Mysql,看看我做的这把小提琴。这是我数据库的简化版本。我现在有一百万条历史记录,问题是查询似乎太慢了。有时需要一分钟才能得到结果。我在sql方面不是很在行。我想我需要索引一些列,但我不确定这些是什么 更新: 我试图解释sql id | select_type | table | type | possible_keys | key | key_len | ref |

看看我做的这把小提琴。这是我数据库的简化版本。我现在有一百万条历史记录,问题是查询似乎太慢了。有时需要一分钟才能得到结果。我在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

首先,您可以为以下列创建聚集索引 id,表1\u id,创建原因,创建地址戳,更新地址戳,在“时间戳”处删除地址戳


然后,代替子查询,将这些结果集放入临时表中,并尝试与临时表和主表联接

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

将索引添加到表1中

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;

创建索引。顺便说一下,货币通常是十进制的,而不是浮动的。此外,您使用的是一个相关子查询。不相关的几乎总是更快。