Mysql query to fetch limited rows of each type

佐手、 提交于 2020-01-03 10:22:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!