I need to retrieve the latest rows with a unique value from my mysql table. Simple table layout is timestamp (now()) and a username column. The table gets new data a couple of times a second, and i need the latest row where username is unique.
SELECT MAX(timestamp) as timestamp, username
FROM bla
WHERE timestamp < (now() - interval 30 minute)
GROUP BY username
ORDER BY timestamp DESC
It seems that this query does not return the latest values, probably because the group is doing something i dont want...
To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.
We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 10 minutes in the past.
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.
If you're trying to look at the last 30 minutes, then I think you want to use "greater than" rather than "less than".
... WHERE timestamp > (now() - interval 30 minute) ...
While what you wrote does work, a faster solution might be to use a LEFT JOIN On the DB I'm working on LEFT JOIN is actually twice as fast w/ the added bonus that you get all the columns from the most recent rows if you want that info:
SELECT *
FROM `bla`
WHERE bla.created_at > (now() - interval 30 minute) AND (next_bla.created_at IS NULL)
LEFT JOIN bla next_bla ON bla.username = next_bla.username AND bla.created_at < next_bla.created_at
ORDER BY bla.created_at DESC
this matches every row in bla w/ the next row by timestamp w/ the same username and picks the rows that don't have a next row (next_bla.created_at IS NULL) i.e. they are the most recent rows.
You can also use a LIMIT clause to improve performance.
This is a good article that explains how GROUP BY works in detail and clear language: http://dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html
Another similar answer by Andomar - MySQL "Group By" and "Order By"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With