Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with limit on rows from one table, not the result set

I'm running a simple query with a join, similar to

SELECT t1.a, t2.b FROM t1 LEFT JOIN t2 ON ... LIMIT 5

As t1 has-many rows in t2 ( any number above 2 ) the LIMIT statement does not return the first 5 rows from t1 and corresponding entries from t2, but 5 rows which usually include 2-3 rows from t1.

How can I write this query to get the first 5 rows from t1 and the corresponding entries from t2?


Using MySQL 5.0.45.

like image 544
Robert Munteanu Avatar asked Jan 18 '10 09:01

Robert Munteanu


2 Answers

SELECT t3.a, t2.b FROM (SELECT * FROM t1 LIMIT 5) t3
LEFT JOIN t2 ON ...

Note that if you use limit without an 'order by' clause, it is not defined which 5 rows you will get. Consider adding an 'order by' clause if this is not what you want.

like image 169
Mark Byers Avatar answered Sep 20 '22 20:09

Mark Byers


This is a classic pagination query. I suggest breaking it down into two queries:

SELECT DISTINCT t1.id FROM t1 LEFT JOIN t2 ON ... LIMIT 5

Take these id's and place them in the following query:

SELECT t1.a, t2.b FROM t1 LEFT JOIN t2 ON ... WHERE t1.id IN (?,?,?,?,?) 
like image 29
hobodave Avatar answered Sep 17 '22 20:09

hobodave