Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LEFT OUTER JOIN with LIMIT

I'm trying to get a certain number of records from a table along with their associated data from another table:

SELECT a.*, b.* FROM tblA a
   LEFT OUTER JOIN tblB b ON a.id = b.target WHERE ... ORDER BY ... LIMIT 0,40

It works, but the problem is that LIMIT seems to limit the number of results and not the number of records I find in A :(

Is there any way to get LIMIT to take into account only the records from A? Because a record from A may have many related records in B and I don't want to limit that

like image 483
thelolcat Avatar asked Feb 17 '14 14:02

thelolcat


People also ask

Can you use limit on a join?

LIMIT and OFFSET Can Work with JOIN.

What is SQL join (+) means?

An SQL Join is an operation that combines records from two or more tables. This is done by matching keys between tables.

What is left outer join with exclusions?

07. LEFT OUTER JOIN with exclusion – replacement for a NOT IN. It gives all records of the left table(Table1) excluding the common elements from right table(Table2).

What is left outer join with example?

A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.


1 Answers

Try putting the limit in a sub-query, and joining on that.

SELECT
  *
FROM
(
  SELECT * FROM tblA WHERE ... ORDER BY ... LIMIT 0,40
)
  AS a
LEFT JOIN
  tblB AS b
    ON a.id = b.target

Many RDBMS will support this, I have no idea about SQLite.

like image 133
MatBailie Avatar answered Nov 15 '22 04:11

MatBailie