I want to make a query in mysql with php and get the last inserted row from each user i have in a database. Let me give you an example.
Suppose we have a table with 10 rows
ID Message User Date inserted
1 lala1 chris 13/02/2010 12:13
2 lala2 john 14/02/2010 12:14
3 lala3 george 15/03/2009 12:00
4 lala4 jack 01/04/2013 11:09
5 lala5 ina 12/08/2012 15:00
6 lala6 chris 13/03/2010 12:13
7 lala7 john 14/01/2010 12:04
8 lala8 george 15/02/2009 12:00
9 lala9 jack 01/03/2013 11:09
10 lala10 ina 12/05/2012 15:00
I want to make a query to get the last inserted rows from chris,john and ina ordered by date. So the result should be this:
5 lala5 ina 12/08/2012 15:00
6 lala6 chris 13/03/2010 12:13
2 lala2 john 14/02/2010 12:14
then after i get the last inserted rows from these users i want to make another query to get the previous last inserted rows for these users again so the result should be:
10 lala10 ina 12/05/2012 15:00
1 lala1 chris 13/02/2010 12:13
7 lala7 john 14/01/2010 12:04
and so on...
Any help appreciated!
If you need to get the last, and then the previous last, and so on, you need to use a ranking function:
row=0 will get the last date, row=1 the previous last, and so on...
Please see fiddle here.
You must use GROUP BY in your SQL query
For first part: (will give you all last insert record for all users. You can apply filter to get only 3 users)
you could also try replacing
with
Replace
User_1
,User_2
andUser_3
with those 3 user namesPlease take a look at
strtotime
found here. With it, you can convert time stamps to an integer and compare them. Also a better method would just be sorting the table by ID and limiting one.