2017-06-21 106 views
0

限制查詢我想要做一個限制相對於ID是這樣的:如何通過ID在MySQL

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

你試過了什麼。 – polka

回答

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; 
+0

感謝兄弟我不知道可以在sql中使用變量 –