Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a limit just for joining table in MySQL query?

Tags:

sql

php

mysql

I have two table named category and content (each category can have many contents), and this is my query

SELECT * FROM categories ca 
LEFT JOIN content co ON co.cat_id=ca.id

I want to apply limit on it that query fetch 10 content for each category.

How should I query for this?

like image 549
mmjj Avatar asked May 18 '15 09:05

mmjj


People also ask

How do I LIMIT a query in MySQL?

Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query would then look like this: $sql = "SELECT * FROM Orders LIMIT 30"; When the SQL query above is run, it will return the first 30 records.

How do I LIMIT the number of rows in a MySQL table?

To limit the number of rows/records a SELECT query can fetch append your SQL Query with LIMIT modifier and the syntax of the SQL Query is given below: your_sql_query LIMIT number_of_records; If the number of records in the database for the query is less than the specified, then all those records would be fetched.

How do I LIMIT a selected query in SQL?

The SQL SELECT LIMIT statement is used to retrieve records from one or more tables in a database and limit the number of records returned based on a limit value. TIP: SELECT LIMIT is not supported in all SQL databases. For databases such as SQL Server or MSAccess, use the SELECT TOP statement to limit your results.


1 Answers

There is not rank function on MySQL.

You should use variables. I wrote this snipped for you. Transpose it to your own schema:

MySQL 5.6 Schema Setup:

--c are categories
create table c ( id int, n varchar(100) );

--p are contents
create table p ( id int, fk_c int, n varchar(100) );

insert into c values
(1, 'A'),
(2, 'B');

insert into p values
(1,1,'a'),
(2,1,'b'),
(3,1,'d'),                          <-- id=3, over the limit set to 2
(4,2,'e');

Query:

select * from (
  SELECT p.*, 
         @n := ( case when @c <> c.id then 1 else @n+1 end) as "num",
         @c := c.id as "prev c"
    FROM c left outer join p on c.id = p.fk_c, 
    (SELECT @n := 0, @c = 0)  r
) p  
    where p.num <= 2                <-- limiting to 2.

Results:

| id | fk_c | n | num | prev c |
|----|------|---|-----|--------|
|  1 |    1 | a |   1 |      1 |
|  2 |    1 | b |   2 |      1 |
                                     <-- id=3 missing ;)
|  4 |    2 | e |   1 |      2 |  
like image 85
dani herrera Avatar answered Sep 30 '22 21:09

dani herrera