I want to select the newest posts from users, I am looking for the most efficient way to do this.
Currently this selects the first post, not the last:
$query = mysql_query("
SELECT *
FROM posts
WHERE toID=fromID
GROUP BY fromID
ORDER BY date DESC LIMIT 3");
Table Structure:
Table: posts
id ToID FromID Post State Date
1 1 1 Hey 0 1325993600
2 1 6 okay yeah 0 1325993615
3 1 2 again 0 1325994600
4 6 6 yeah2 0 1325995615
so from this above example it would return id: 1 and 4.
toID=fromID is just to get the post that is a status message, meaning the user posted something on their own page, not someone elses.
I want to get the most recent status from the last 3 users that have updated their status.
The ID thing would still work theoretically, provided that the ID’s never change…
I would recommend using a timestamp field in the table structure called “date” and use the “CURRENT_TIMESTAMP” as default value, this will auto-populate the date/time on the record upon insert…
Order by this field DESC, limit x
Also, I have experienced many cases of the wrong data appearing thanks to grouping… Make sure your data is correct before ORDER BY and LIMIT is applied
For getting posts from user1 to user1 there’s no need to group by:
For getting posts from * to user1:
For getting posts from * to user1, only unique users:
Somtimes you will run into the problem where GROUPED records are not ordered by ORDER BY, because the ORDER BY is applied to the result AFTER the grouping is applied… To achieve a workaround:
To Get the last 3 users who have most recently sent themselves a post: