慢mysql查询(使用IN)

时间:2017-02-18 21:02:36

标签: mysql performance

我有一个简单的查询:

SELECT Description, Temp1, Temp2, SensorData.DateAndTime
FROM SensorData 
     INNER Join Sensors on Sensors.ChipId=SensorData.RockID 
WHERE SensorData.Id in (Select max(Id) LastRecord 
                        From SensorData  
                        Group by RockId)
ORDER BY DhtTemp;

需要3秒钟。如果我删除内部选择查询并将其替换为查询结果,则需要.1秒。如果我单独运行内部查询,则需要0.1秒。如果我删除Join to Sensors,它会在0.5秒内运行(这没关系。)有什么建议吗?我在Id列上有索引,这是INT。

2 个答案:

答案 0 :(得分:1)

ChipId表中的

Sensors用于连接条件,而内部选择查询中的RockIdgroup by列名称,您是否尝试将此列编入索引?

在另外尝试此查询:

 SELECT Description, Temp1, Temp2, myData.DateAndTime
 FROM
     (SELECT *,max(id) as mymax FROM SensorData 
      Group by RockId
      Order by id desc
      ) as myData
 INNER Join Sensors on Sensors.ChipId= myData.RockID 
 WHERE SensorData.Id = mydata.mymax 
 ORDER BY DhtTemp;

答案 1 :(得分:1)

大多数where in (select ...)个查询可以被重写(通常由优化器自动重写,但不总是)作为连接;试试这个:

select Description, Temp1, Temp2, a.DateAndTime
from SensorData a
left join SensorData b on b.RockId = a.RockId
    and b.ID > a.ID
join Sensors on Sensors.ChipId = a.RockID 
where b.ID is null
order by DhtTemp

在英语中,这意味着"只返回不具有更高ID的SensorData行。

确保您拥有RockId的索引。