Reputation: 193
I have a simple query:
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;
It takes 3 seconds. If I remove the inner select query and replace it with the results from the query it takes .1 seconds. If I run the inner query alone it takes .1 seconds. If I remove the Join to Sensors it runs in .5 seconds (which would be fine.) Any advice? I have Indexes on The Id columns which are INT.
Upvotes: 3
Views: 46
Reputation: 425418
Most where in (select ...)
queries can be rewritten (often automatically by the optimiser, but not always) as joins; try this:
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
In English, this means "only return SensorData rows that don't have a higher ID`.
Make sure you have in index on RockId
.
Upvotes: 1
Reputation: 2855
ChipId
in Sensors
table is used in join condition and RockId
in inner select query is group by
column name, have you tried to index this columns?
in Addition try this query:
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;
Upvotes: 1