索引在从查询派生的表中不起作用

时间:2019-01-31 09:52:45

标签: mysql

我正在优化查询。我的查询需要6到10分钟才能响应,因此我的索引无法正常工作。我需要将其减少到30秒以下。

Sample Table:
Table 1: Snapshots
Columns: id , type, instance, location,x, y, z, timestamp. Where id is primary key
index 1 = (type,instance, timestamp)
index 2 = location

Table 2: SnapshotMeta
Columns: type, instance, classifier where all the columns are composite primary key
Index : (classifier, type, instance)

具有1亿条记录的表1和具有5百万行的表2。

类型/实例/时间戳/ x的组合构成唯一记录。每次,我都会得到一组x的值(每个类型/实例)。我使用时间戳进行存储,以了解每次更改的值。

我需要根据我传递的分类器,时间戳值获得唯一的位置。

查询1:

SELECT DISTINCT mt.location 
from ( SELECT t1.location, MAX(t1.timestamp) AS maxtimestamp , 
col.instance, col.type from SnapshotMeta col 
inner join Snapshots t1 on col.classifier in ( My classifiers) 
AND col.type = t1.type AND col.instance=t1.instance 
AND t1.timestamp <= MYTIMESTAMP 
group by t1.instance) t 
inner join Snapshots mt on mt.type = t.type  and  mt.instance = t.instance 
AND mt.timestamp = t.maxtimestamp 
ORDER BY t.location;

以上查询需要5到10分钟才能回复。

查询2:

select distinct location 
from (select max(timestamp) mt , type, instance 
from Snapshots 
where timestamp <= MYTIMESTAMP 
AND type in 
(select distinct type from SnapshotMeta where classifier in ("rural")) 
group by type, instance) t inner join Snapshots t1 on t.type=t1.type 
AND t.instance=t1.instance AND t1.timestamp=t.mt;

以上查询需要2到4分钟才能回复。

在两个查询索引中,派生表均不起作用。还有其他方法可以简化我的查询,使其工作更快。

0 个答案:

没有答案