2017-02-18 130 views
3

我有一個簡單的查詢:慢速MySQL的查詢(使用IN)

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秒。如果我刪除內部選擇查詢並將其替換爲查詢中的結果,則需要花費0.1秒。如果我單獨運行內部查詢,則需要.1秒。如果我刪除加入傳感器它運行在0.5秒(這將是好的。)任何建議?我有關於Id列的索引是INT。

回答

1

ChipId in Sensors表用於連接條件和RockId在內部選擇查詢是group 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; 
+0

我喜歡它。我在內部查詢中添加了where子句,以減少返回的行數,並且速度非常快。謝謝! – Jay

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

+0

是的,一個有效的查詢,但很難快! – Strawberry