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
LIMIT and OFFSET Can Work with JOIN.
An SQL Join is an operation that combines records from two or more tables. This is done by matching keys between tables.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With