简体   繁体   中英

Slow mysql query (using IN)

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.

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;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM