MySQL group by a certain type and select the latest row?
Imagine a table with columns type, date, message. And some rows looking like this (type | date | message):
1 | 1310572318 | Hello
1 | 1310572317 | Hi
2 | 1310572315 | Wassup
3 | 1310572312 | Yo
3 | 1310572311 | He开发者_运维技巧y
3 | 1310572309 | Eyo
1 | 1310572305 | Hello
1 | 1310572303 | Good Day
Is it possible to group them by type, and selecting the latest (ordered by date) so the result would be:
1 | 1310572318 | Hello
2 | 1310572315 | Wassup
3 | 1310572312 | Yo
1 | 1310572305 | Hello
I'm pretty sure I have to use some MySQL Aggregate functions, but I'm not very good at them, so I'm asking for a little bit of help here.
There isn't any aggregate that can use a different column so that you could get the message with the latest date.
This could be helpful:
SELECT
`type`,
MAX(`date`) AS `max_date`,
(SELECT `t2`.`message` FROM `table` AS `t2` WHERE `t2`.`type` = `t1`.`type` ORDER BY `t2`.`date` DESC LIMIT 1)
FROM `table` AS `t1`
GROUP BY `type`
Please try:
Select type, date, message from tableName
group by type
having min(date)
Please note, that the last line is not valid
1 | 1310572305 | Hello
Assuming that your dates are represented as integers like you have showing here, you can try the following:
SELECT type, MAX(date), message
FROM myDB.myTable
GROUP BY type;
Unless i'm missing something fundamental here, this should do the trick.
精彩评论