Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you apply LIMIT on MySQL before LEFT JOIN another?

For example:

SELECT * FROM table_1 LIMIT 5 
LEFT JOIN table_2 AS table_1.id = table_2.id 
WHERE 1

Otherwise the engine takes all of table_1 before applying the join, then limiting which can slow the query down massively (with massive tables).

like image 584
joedborg Avatar asked Sep 13 '11 16:09

joedborg


People also ask

Can you use LEFT join twice?

Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis.

Does MySQL allow the use of order by and limit in the same query?

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.

Can we use limit in MySQL?

The MySQL LIMIT ClauseThe LIMIT clause is used to specify the number of records to return. The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

Can LEFT join result in more rows?

Left joins can increase the number of rows in the left table if there are multiple matches in the right table.


1 Answers

You can do it by joining on a subquery instead of an actual table. Something like this should work:

SELECT * FROM
    (SELECT * FROM table_1 LIMIT 5) as subq
    LEFT JOIN table_2 ON subq.id = table_2.id WHERE 1
like image 137
Asaph Avatar answered Sep 17 '22 02:09

Asaph