Here’s my table structure:
CREATE TABLE USER (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
`status` VARCHAR(50),
`dateupdated` DATETIME
) ENGINE = INNODB;
If the data, has an ID as primary key, then the username can be repeated, let’s say I have 3 users, and all of them had a status update yesterday and today. Now my question is, how to select only the latest status updates from each user ?, here’s my solution
SELECT user.`username`, latest.status AS latest_status , user.`dateupdated`
FROM USER
LEFT JOIN USER AS latest ON user.`id` = latest.id
ORDER BY dateupdated DESC;
…but it seem wrong, because it “also” printed out the data dated yesterday, so how to do that in order to get the exact latest data only for each users and avoid printing out the past datas?
You’re almost there, but to get the latest per user you have to add an extra sorting condition in your JOIN, and a where condition:
What this does is join
USERto itself not only within username, but such thatu‘sdateupdatedis less thanu2s. Since this aLEFT JOIN, if there is au.dateupdatedsuch that there is no greateru2.updatedfor the sameusername, then theu2.updatedis set to NULL.But these
u.dateupdatedare precisely the maximumdateupdatedfor that user, and hence we add theWHEREcondition in to grab these rows.