Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL WHERE, LIMIT and pagination

Tags:

mysql

I have tables: documents, languages and document_languages. Documents exist in one or more languages and this relationship is mapped in document_languages.

Imagine now I want to display the documents and all of its languages on a page, and paginate my result set to show 10 records on each page. There will be a WHERE statement, specifying which languages should be retrieved (ex: en, fr, it).

Even though I only want to display 10 documents on the page (LIMIT 10), I have to return more than 10 records if a document has more than one language (which most do).

How can you combine the WHERE statement with the LIMIT in a single query to get the records I need?

like image 498
stef Avatar asked Sep 06 '13 09:09

stef


People also ask

How can limits be used in pagination?

LIMIT n is an alternative syntax to the FETCH FIRST n ROWS ONLY. The OFFSET clause specifies the number of rows of the result table to skip before any rows are retrieved, and must be used with the LIMIT clause. The OFFSET clause instructs the server where to start returning rows within the query result.

How do I LIMIT data 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 does LIMIT and offset work in MySQL?

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 that are offset and count. The value of both the parameters can be zero or positive integers.


1 Answers

Use sub query to filter only documents records

select * from 
(select * from documents limit 0,10) as doc, 
languages lan, 
document_languages dl
where doc.docid = dl.docid
and lan.langid = dl.langid

Check sub query doc as well

http://dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html http://dev.mysql.com/doc/refman/5.0/en/subqueries.html

like image 158
Rakesh Soni Avatar answered Oct 06 '22 01:10

Rakesh Soni