问题
I have a Table in MYSql called companies and each companies has a type say type 1, type 2 type 3,
example :
id company_name company_type
===============================
1 test1 3
2 xyz 2
3 ashdasdjk 2
4 test 4 1
5 test 3
6 ahsdkjsg 1
7 TCS 2
and so on ...
now i want to write a query to fetch results such that i get 20 companies of type 1, 20 companies of type 2 and 20 companies of type 3... i mean i want to fetch maximum of 20 companies of each type
I am using Codeigniter..
回答1:
select * from (
select
c.*,
@rn := if(company_type != @ct, 1, @rn + 1) as rownumber,
@ct := company_type
from
companies c
, (select @rn := 0, @ct := null) var_init
order by
company_type
) comp
where rownumber <= 20;
来源:https://stackoverflow.com/questions/22399508/mysql-query-to-fetch-limited-rows-of-each-type