I have a query with subquery but subquery table has approximately 500.000 records and runing this query takes too long. How can I speed up this query? Any suggestions:
SELECT ID, VehicleID, Plate, VehicleType,
COALESCE(
(SELECT EngineState
FROM Locations
WHERE Locations.VehicleID = Clients.VehicleID ORDER BY ID DESC LIMIT 1),
0
) EngineState
FROM Clients
WHERE ID IN (SELECT ClientID FROM UserClients WHERE UserID=@UserID);
There are 3 more columns which query last record from Locations table:
COALESCE(
(SELECT EngineState FROM Locations
WHERE Locations.VehicleID = Clients.VehicleID ORDER BY ID DESC LIMIT 1),
0
) EngineState
As I see sorting the results in Locations table is the performance factor there. Locations table if filled every minute by 1000 vehicles' location data. x, y, speed ...