I have a table that stores locations of users. I would like to select the latest location of every user.
What I’ve tried
SELECT lat, lng, address, idUser, timestamp FROM locations ORDER BY timestamp DESC LIMIT 1
SELECT lat, lng, address, idUser, MAX(timestamp) FROM locations
Those two, of course, gave me the last location among all users. The structure of the table is simple:
CREATE TABLE `locations` (
`idLocation` int(11) NOT NULL auto_increment,
`idUser` int(11) NOT NULL,
`address` varchar(255) NOT NULL,
`lat` float(10,6) NOT NULL,
`lng` float(10,6) NOT NULL,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`idLocation`),
KEY `idUser` (`idUser`)
)
I found the solution in this page, using a self join. Get the latest timestamp for each user and then get the rest of the row by self-joining.
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/