There are many questions out there close to this, but I can't find one with a solid example of how to do quite what I want. I need to get a single max row for each group when the maximum value is not unique within a group. Here's a table:
| id | source | name | message_time |
|----|--------|------|--------------|
| 1 | a | cool | 2020-08-18 |
| 2 | a | cool | 2020-08-18 |
| 3 | a | neat | 2020-08-02 |
| 4 | b | nice | 2020-08-19 |
| 5 | b | wow | 2020-08-17 |
For each source, I need a single full row associated with the maximum message_time. Since the max message time is not unique within a group, both of these are valid outputs:
| id | source | name | message_time |
|----|--------|------|--------------|
| 1 | a | cool | 2020-08-18 |
| 4 | b | nice | 2020-08-19 |
| id | source | name | message_time |
|----|--------|------|--------------|
| 2 | a | cool | 2020-08-18 |
| 4 | b | nice | 2020-08-19 |
When there are multiple candidates for max, I just want to randomly select a single row. How can I achieve this with a mysql query?
I'm using MySQL 5.7
Edit:
So I messed around some more and realized this works:
SELECT table.*
FROM (
SELECT source FROM table
GROUP BY source
) groups
LEFT JOIN table
ON id = (
SELECT id FROM table
WHERE source = groups.source
ORDER BY message_time desc
LIMIT 1
);
I think I even understand why it works, but I don't know what no good, very bad practices I am doing here. Also, can it be simplified?