MySQL get set of data with distinct values

ぐ巨炮叔叔 提交于 2019-12-25 08:16:37

问题


I have a simple problem; one which I thought would have a simple solution. Imagine a Table like this:

Name           Timestamp              Data
Bob            2011-01-01 01:00:00    Hi
Alice          2011-02-02 02:00:00    Hello
Alice          2011-03-03 03:00:00    Hello
Bob            2011-04-04 04:00:00    Bye
Charlie        2011-05-05 05:00:00    Cheese
Charlie        2011-06-06 06:00:00    Toast

All I want is to be able to run a query that shows the most recent entry for each Name. So with the above table, I would like an output like this:

Name           Timestamp              Data
Bob            2011-04-04 04:00:00    Bye
Alice          2011-03-03 03:00:00    Hello
Charlie        2011-06-06 06:00:00    Toast

Ordered by Data. I can't figure out how to do this. I though I could just do:

SELECT DISTINCT(Name), timestamp, Data FROM Table ORDER BY Data

But this doesn't work. Any help would be most appreciated, Cheers.


回答1:


Use this query to get last unique values,

SELECT * FROM (select * from `table` order by date DESC) t group by name



回答2:


SELECT DISTINCT Name, Timestamp, Data
FROM Table
WHERE Timestamp =
    (
     SELECT MAX(Timestamp)
     FROM Table AS tempTable
     WHERE Table.Name = tempTable.Name
    )



回答3:


select t1.* from table as t1
inner join (
select name,max(`timestamp`) as `timestamp`
from table
group by name) as t2
on t1.name = t2.name and t1.`timestamp` = t2.`timestamp`


来源:https://stackoverflow.com/questions/5381859/mysql-get-set-of-data-with-distinct-values

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