Search code examples
mysqlsqllimit

How to limit by id a query in MySQL


I want to make a limit with respect to id like this:

My table:

id   id_propertie   description
------------------------------
 1       1           Some text
 2       1           Some text
 3       2           Some text
 4       2           Some text
 5       2           Some text
 6       3           Some text
------------------------------

I want this

SELECT * FROM propertie limit 2


id   id_propertie   description
------------------------------
 1       1           Some text
 2       1           Some text
 3       2           Some text
 4       2           Some text
 6       3           Some text
------------------------------

Solution

  • In MySQL, the easiest way is to use variables:

    select p.*
    from (select p.*,
                 (@rn := if(@id = id, @rn + 1,
                            if(@id := id, 1, 1)
                           )
                 ) as rn
          from propertie p cross join
               (select @id := 0, @rn := 0) params
          order by id_propertie, id
         ) p
    where rn <= 2;