如何在MySQL中通过id限制查询

时间:2017-06-21 21:03:49

标签: mysql sql limit

我想对这样的id做出限制:

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
------------------------------

我想要这个

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
------------------------------

1 个答案:

答案 0 :(得分:1)

在MySQL中,最简单的方法是使用变量:

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;