Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the latest rows in MySQL?

I want to select the latest rows of a specific table that has 5 items in MySQL. The table looks like:

  • id (auto increase)
  • to
  • from
  • time stamp
  • text

The data is something like:

|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

I want to select * WHERE to = 'user01' and the latest data (maybe by "id" or "time stamp"). The "from" can be numerous but each same "from" data can appear just once.


Anyway, the selected data will be:

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

Could it be done? Thanks for taking time reading my question :)

like image 431
Chi-Wei Shih Avatar asked Sep 15 '11 09:09

Chi-Wei Shih


2 Answers

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
             )

It's better to avoid naming tables and fields with keywords like to, from and timestamp.

like image 120
ypercubeᵀᴹ Avatar answered Oct 12 '22 11:10

ypercubeᵀᴹ


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

...will give you the newest entry.

like image 2
Niko Avatar answered Oct 12 '22 10:10

Niko