Need help to optimize my query, currently it runs approximately 22secs and I have 1.1 million rows in that table. Here is my query. This query is returning the users latest time in.
SELECT
t.id, t.user_id, t.created
FROM
timesheets t
WHERE
t.user_id IN (41649 , 41901,41899,41482,41648,41897,41652,
41483,41900,41143,41907,16,42191,42195,42194,42136,42193,42190,42484,42485,42486,42504,
42052,42797,42997,42868,42847,42505,42964)
AND t.id = (SELECT
MAX(sub_t.id)
FROM
timesheets AS sub_t
WHERE
sub_t.user_id = t.user_id
AND sub_t.description = 'in')
I also have table indexes for this table (id, user_id, created, description). Any suggestion is very much appreciated. Thanks
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `timesheets` ADD INDEX `timesheets_idx_id_descriptio_user_id` (`id`,`description`,`user_id`);
SELECT
timesheets1.id,
timesheets1.user_id,
timesheets1.created
FROM
timesheets AS timesheets1
LEFT JOIN
timesheets AS timesheets2
ON (
timesheets2.user_id = timesheets1.user_id
AND timesheets2.description = 'in'
)
AND (
timesheets1.id < timesheets2.id
)
WHERE
(
timesheets1.user_id IN (
41649, 41901, 41899, 41482, 41648, 41897, 41652, 41483, 41900, 41143, 41907, 16, 42191, 42195, 42194, 42136, 42193, 42190, 42484, 42485, 42486, 42504, 42052, 42797, 42997, 42868, 42847, 42505, 42964
)
AND 1 = 1
)
AND (
timesheets2.id IS NULL
)