Skip to content
Advertisement

SQL left join exclude non matching records

I’m working on this query (running on MySQL 5.6):

I thought LEFT JOIN clause will produce a record even if there’s not a matching record in table noleggio_veicoli but this doesn’t happen. The result include just records where a match is found between veicoli_contratti and noleggio_veicoli. I tried also adding OR noleggio_veicoli.id IS NULL in WHERE clause but it’s not the solution. How can I fix this? I created an SQL fiddle to try this here

Advertisement

Answer

Your understand is correct. However, the where clause is “undoing” the LEFT JOIN. Why?

You have conditions such as this:

Well, NULL fails those conditions so non-matches are filtered out. This condition (along with other conditions) should be included in the ON clause. For this one, it looks like:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement