I have two tables user and log. I would like to join the user table with logs and get the latest log entry. I have noted that using the group by the rows inside the group are not sorted. Therefore I am not able to retrieve the latest log row.
USER:
ID | Name
--------------------
1 | John
2 | Mike
LOG:
L_ID | ACTION | DATE | USERID
----------------------------------
1 | OPEN | '1 DEC' | 1
2 | CLOSE | '3 DEC' | 1
3 | WRITE | '2 DEC' | 1
4 | OPEN | '5 DEC' | 2
5 | CLOSE | '3 DEC' | 2
With this table the result I would like to have is:
2 Mike 4 OPEN '5 DEC'
1 Jhon 2 CLOSE '3 DEC'
I know that the following query is not working since rows inside the group are not sorted:
Select * from user join log on ID=USERID group by ID order by DATE DESC,L_ID
Also the following is not working since only the correct date is returned but not the actions:
Select ID,Name,Action,Max(Date) from user join log on ID=USERID group by ID order by DATE DESC, L_ID
Any idea suggestion how to write the query that will return the correct result?
This is pretty straightforward:
This should work in MySQL, hence sqlite too hopefully.. This may not be the best optimized, I hope to see someone more knowledgeable giving the exact query.
This supposes your date field is proper date time field and not strings. These links might give you some more idea.
Please also note that ordering by ID is not safe, it need not be always first record, lesser id.. it depends. So always have a safe second sort column, something like weight or so which stands for ‘time’ or your own custom rank.