MySQL group by a certain type and select the latest row?

ⅰ亾dé卋堺 提交于 2019-12-23 16:43:19

问题


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 | Hey
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.


回答1:


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`



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/6693796/mysql-group-by-a-certain-type-and-select-the-latest-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!