Search code examples
mysqlsqllimitforum

how to get a single row for each user?


sorry for the title, i don't know how to explain it better...

i have a forum and i want to make a sort of achievement system in php

i want to know when users with posts>10 posted their 10th message...

the post table is like

post_id | post_date | userid | post_message | ...

i can get this result for each user with

select userid, post_date from posts where userid=1 order by post_date limit 9,1

but i need a resultset like

id | date
id | date
id | date

it can only be done with procedures?


Solution

  • Try this query

    select 
        * 
    from (
        select 
           @rn:=if(@prv=userid, @rn+1, 1) as rid, 
           @prv:=userid as userid,
           post_message
        from 
           tbl
        join 
           (select @rn:=0, @prv:=0) tmp
        order by 
           userid, 
           post_date) tmp 
    where 
        rid=10
    

    SQL FIDDLE

    | RID | USERID | POST_MESSAGE |
    -------------------------------
    |  10 |      1 |       asdasd |
    |  10 |      2 |       asdasd |