Home >Database >Mysql Tutorial >Does an INNER JOIN After an OUTER JOIN Negate the OUTER JOIN's Effect?
Nested SQL Joins: INNER JOINs and OUTER JOINs
Does an INNER JOIN
following an OUTER JOIN
cancel out the OUTER JOIN
's effect? And should INNER JOIN
s always precede OUTER JOIN
s in multi-join queries?
The answer is nuanced. A subsequent INNER JOIN
will only negate the OUTER JOIN
if its ON
clause requires the presence of columns that could be NULL
due to the OUTER JOIN
. Simply rearranging the joins won't fix this; you'll need to change the INNER JOIN
to a suitable OUTER JOIN
.
Let's illustrate:
Example 1 (Reordering Doesn't Matter):
<code class="language-sql">SELECT * FROM person LEFT JOIN address ON person.address_id = address.id INNER JOIN email ON person.email_id = email.id</code>
Here, reordering the joins won't change the results.
Example 2 (Reordering Matters):
<code class="language-sql">SELECT * FROM person LEFT JOIN address ON person.address_id = address.id INNER JOIN city ON address.city_id = city.id</code>
The second ON
clause necessitates a non-NULL
address.city_id
. This defeats the LEFT OUTER JOIN
, filtering out person
records without a matching city
via address
. To correct this, replace the INNER JOIN
with a LEFT OUTER JOIN
.
Best Practices:
While not strictly mandatory, it's generally recommended to place INNER JOIN
s before OUTER JOIN
s. This improves readability and clarifies the query's essential filtering conditions. Furthermore, RIGHT OUTER JOIN
s are often less preferred and can usually be rewritten using LEFT OUTER JOIN
s for better clarity and maintainability.
The above is the detailed content of Does an INNER JOIN After an OUTER JOIN Negate the OUTER JOIN's Effect?. For more information, please follow other related articles on the PHP Chinese website!