I have two tables
users
user_id | name
1 | John
2 | Jess
user_data (in_out - 1 indicate in, 0 indicate out)
id | user_id | in_time | out_time | in_out
1 | 1 | 2019-05-14 09:15:32 | 2019-05-14 10:45:32 | 0
2 | 1 | 2019-05-15 10:15:32 | 0000-00-00 00:00:00 | 1
3 | 2 | 2019-05-16 11:15:32 | 2019-05-16 12:15:32 | 0
I want to get latest entries of each user, but group by and order by did not work well.
First I tried following way, but this is not give latest records (I want to get record id 2 and 3 from user_data table, but it returns record id 1 and 3)
SELECT *, user.user_id as user_key
FROM user
LEFT JOIN user_data ON user_data.user_id = user.user_id
GROUP BY user_data.user_id ORDER BY user_data.id DESC
Secondly I tried following way, I wrote this query following an answer of stackoverflow, but it did not work.
SELECT *, user.user_id as user_key
FROM user
LEFT JOIN
(
SELECT MAX(user_data.id) as max_record_id, user_data.user_id
FROM user_data
GROUP BY user_data.user_id
) u2 ON u2.user_id = user.user_id
GROUP BY user_data.user_id ORDER BY user_data.id DESC
Someone please help me to solve this issue. Thank You