retrieve the last inserted row from each user in database

落爺英雄遲暮 提交于 2019-12-06 09:49:36

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.

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

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.

You must use GROUP BY in your SQL query

SELECT DISTINCT User, MAX(Date_inserted) FROM yourTable GROUP BY User
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!