I have one table with user posts. I need to show from 1 to maximum n post from each user per each day.
Example:
post_id|user_id|post_datetime|post_text
1
Try this awful SQL code :)
select post_id, user_id, post_datetime, post_text from (
select posts.*,
if (user_id = @prev_user and date(post_datetime) = date(@prev_day),
@row := @row + 1, @row := 1) idx,
@prev_user := user_id,
@prev_day := post_datetime
from posts, (select @row := 1, @prev_user := null, @prev_day := null) init
order by date(post_datetime), user_id, post_datetime desc
) s
where s.idx <= 2
Result:
+---------+---------+---------------------------------+----------------+
| POST_ID | USER_ID | POST_DATETIME | POST_TEXT |
+---------+---------+---------------------------------+----------------+
| 4 | 100 | December, 01 2012 04:00:00+0000 | lorem ipsum 4 |
| 2 | 100 | December, 01 2012 02:00:00+0000 | lorem ipsum 2 |
| 3 | 101 | December, 01 2012 03:00:00+0000 | lorem ipsum 3 |
| 5 | 102 | December, 01 2012 05:00:00+0000 | lorem ipsum 5 |
| 6 | 100 | December, 02 2012 03:00:00+0000 | lorem ipsum 6 |
| 10 | 101 | December, 02 2012 07:00:00+0000 | lorem ipsum 10 |
| 9 | 101 | December, 02 2012 06:00:00+0000 | lorem ipsum 9 |
| 7 | 102 | December, 02 2012 04:00:00+0000 | lorem ipsum 7 |
+---------+---------+---------------------------------+----------------+
Fiddle here.
I thought the ordering would be more suitable if it was descending by date, as you're actually getting the top 2 closest to the current date.