开发者

Simple MYSQL distinct select

开发者 https://www.devze.com 2023-03-20 11:37 出处:网络
If I have a table with two columns, name and timestamp, and a bunch of rows that will have shared names. How do I select the most recent row of each set of ro开发者_StackOverflowws that shares the sam

If I have a table with two columns, name and timestamp, and a bunch of rows that will have shared names. How do I select the most recent row of each set of ro开发者_StackOverflowws that shares the same name?

Thanks!


SELECT name, MAX(timestamp) FROM Table1 GROUP BY name

EDIT: Based on the comment, please try the following:

SELECT name, timestamp, col3, col4
FROM   Table1 t1
WHERE  timestamp = (SELECT MAX(t2.timestamp)
              FROM Table1 t2
              WHERE t1.name = t2.name);

Added by Mchl

Version with no dependent subquery (should perform better)

SELECT 
  t1.name, t1.timestamp, t1.col3, t1.col4
FROM   
  Table1 AS t1
CROSS JOIN (
  SELECT 
    name, MAX(timestamp) AS timestamp
  FROM 
    Table1
  GROUP BY
     name
) AS sq
USING (name,timestamp)


Then you need a subquery:

SELECT columns 
FROM Table1 t1
WHERE row_id = (SELECT row_id 
                FROM table1 t2
                WHERE t1.name = t2.name
                ORDER BY timestamp DESC 
                LIMIT 1)
GROUP BY name

Edited, forgot the group by name

0

精彩评论

暂无评论...
验证码 换一张
取 消