Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql query to fetch limited rows of each type

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

like image 297
Mohan Avatar asked Mar 14 '14 08:03

Mohan


People also ask

How do I limit the number of rows in MySQL query?

In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count. The value of both the parameters can be zero or positive integers.

How do we limit which rows are returned by a query?

The SQL LIMIT clause restricts how many rows are returned from a query. The syntax for the LIMIT clause is: SELECT * FROM table LIMIT X;. X represents how many records you want to retrieve. For example, you can use the LIMIT clause to retrieve the top five players on a leaderboard.

How will you limit a MySQL query to display only top 10 rows?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I get last 10 rows in SQL?

SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records.


1 Answers

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;
like image 163
fancyPants Avatar answered Sep 20 '22 06:09

fancyPants