I want to select the latest rows of a specific table that has 5 items in MySQL. The table looks like:
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 :)
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
.
SELECT * FROM tablename WHERE to = 'user01' ORDER BY timestamp DESC LIMIT 1
...will give you the newest entry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With