I wanted to ask is there a way to know which table should be right or left while using joins in SQL? for example I have two tables that I am joining, for example,
SELECT * FROM filtered_numbers LEFT JOIN telecoms ON filtered_numbers.TelecomID = telecoms.ID
Now The 'filtered_numbers' table has 200 records while 'telecoms' has only 5. My question is that will there be a difference in performance / efficiency of the db if I interchange the position of these two tables in the query? If yes, why?
This answer is a little complicated. The first thing to note is that
FROM filtered_numbers LEFT JOIN
telecoms
ON filtered_numbers.TelecomID = telecoms.ID
is semantically quite different from:
FROM telecoms LEFT JOIN
filtered_numbers
ON filtered_numbers.TelecomID = telecoms.ID
Switching only the tables changes the meaning of the query. The execution plan and performance will be different. You will get the same query if you change the LEFT JOIN
to a RIGHT JOIN
in this case, but as Strawberry points out, LEFT JOIN
is much preferred.
This is simplified though and not always true. If you have a complicated query, the ordering of the JOIN
s can make a difference. Now, LEFT JOIN
has a "driving" table (where all rows are kept) so there are many fewer options. But if you have INNER JOIN
s, then ordering can matter.
In fact, it can matter so much that MySQL offers optimizer hints just to control join order .
So, the answer to your question is:
RIGHT JOIN
will not affect performance because there is really only one option for the optimizer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.