问题
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!
回答1:
If you need to get the last, and then the previous last, and so on, you need to use a ranking function:
SELECT *
FROM (
SELECT
Users.*,
CASE WHEN @lst=User THEN @row:=@row+1 ELSE @row:=0 END row,
@lst:=User
FROM
Users
WHERE
User IN ('ina','chris','john')
ORDER BY
User, Date_ins DESC
) s
WHERE
row=0
row=0 will get the last date, row=1 the previous last, and so on...
Please see fiddle here.
回答2:
For first part: (will give you all last insert record for all users. You can apply filter to get only 3 users)
SELECT t1.*
FROM Users t1
INNER JOIN (
SELECT User, MAX(Date_Inserted) as MaxDate
FROM Users
GROUP BY User
) t2 ON t1.User = t2.User AND t1.Date_Inserted = t2.MaxDate
you could also try replacing
GROUP By User
with
WHERE User IN (User_1, User_2, User_3)
Replace User_1
, User_2
and User_3
with those 3 user names
回答3:
Please 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.
回答4:
You must use GROUP BY in your SQL query
SELECT DISTINCT User, MAX(Date_inserted) FROM yourTable GROUP BY User
来源:https://stackoverflow.com/questions/16368162/retrieve-the-last-inserted-row-from-each-user-in-database