如何选择MySQL中的最新行?

时间:2011-09-15 09:00:02

标签: php mysql select where

我想选择MySQL中有5个项目的特定表的最新行。 该表看起来像:

  • id(自动增加)
  • 时间戳
  • text

数据类似于:

|id | to     | from   | time stamp | text
| 1 | user01 | user02 | 2011-09-01 | text1
| 2 | user01 | user02 | 2011-09-02 | text2
| 3 | user02 | user01 | 2011-09-02 | text3
| 4 | user01 | user03 | 2011-09-03 | text4
| 5 | user01 | user04 | 2011-09-03 | text5
| 6 | user01 | user03 | 2011-09-04 | text6
| 7 | user03 | user01 | 2011-09-05 | text7

我想要select * WHERE to = 'user01'和最新数据(可能是“id”或“时间戳”)。 “from”可以很多,但每个相同的“from”数据只能出现一次。


无论如何,所选数据将是:

| 2 | user01 | user02 | 2011-09-02 | text2
| 5 | user01 | user04 | 2011-09-03 | text5
| 6 | user01 | user03 | 2011-09-04 | text6

可以吗? 感谢您花时间阅读我的问题:)

7 个答案:

答案 0 :(得分:4)

SELECT t.* 
FROM
      TableX AS t
  JOIN
      ( SELECT DISTINCT `from` AS f
        FROM TableX
        WHERE `to` = 'user01'
      ) AS df
    ON 
      t.id = ( SELECT tt.id
               FROM TableX AS tt
               WHERE tt.`to` = 'user01'
                 AND tt.`from` = df.f
               ORDER BY tt.`timestamp` DESC
               LIMIT 1
             )

最好避免使用tofromtimestamp等关键字命名表格和字段。

答案 1 :(得分:2)

SELECT * FROM tablename WHERE to = 'user01' ORDER BY timestamp DESC LIMIT 1

...会给你最新的条目。

答案 2 :(得分:2)

我认为您正在寻找SELECT DISTINCT user_from FROM table WHERE user_to='user1' ORDER BY id DESC

DISTINCT只会为每个user_from值返回一行。

答案 3 :(得分:1)

一种可能性是这样的:

SELECT * FROM tbl WHERE id IN (
    SELECT MAX(id) FROM tbl
    WHERE to = 'user01'
    GROUP BY from
);

但我不知道它是否符合您的要求,每个“来自”只能出现一次。

答案 4 :(得分:1)

如果您想要每个唯一from用户的最新行:

SELECT `from`, MAX(`id`), `to` FROM `tablename` WHERE `to`='user01' GROUP BY `from`

(我认为获取id的MAX可能比时间戳的MAX更快)

答案 5 :(得分:1)

你可以这样做:

SELECT to, from, max(timestamp) FROM <table> WHERE to = 'user01' GROUP BY from

要获取相关文本,您也可以这样做,但效率不高

SELECT * FROM <table> 
WHERE 
    CONCAT([to], [from], [timestamp]) 
    IN 
    (
     SELECT CONCAT([to], [from], MAX([timestamp])) FROM <table> 
     WHERE [to] = 'user01' GROUP BY [from]
    )

答案 6 :(得分:-1)

SELECT * FROM `table_name` WHERE `to` = 'user01' ORDER BY `timestamp` DESC LIMIT 0,1