Question

First query:

SELECT SUM(Rent.paid) AS Rent__summed_rents 
FROM rents AS Rent 
LEFT JOIN contracts ON contracts.id = Rent.id 
LEFT JOIN units ON contracts.unit_id = units.id AND units.owner_id = 29

Second query:

SELECT SUM(Rent.paid) AS Rent__summed_rents 
FROM rents AS Rent 
LEFT JOIN contracts ON contracts.id = Rent.id 
LEFT JOIN units ON contracts.unit_id = units.id
WHERE units.owner_id = 29

I should point that the result is not the same!

Était-ce utile?

La solution

The difference is the the filtering condition.

For example, in your first query, it is going to select the sum(rent.paid) regardless if either of the joins actually produce records. The benefit here is that if you need data regardless of the join working, but do want to filter the join, then you put the conditional filter on the join clause itself.

In your second query, with the conditional filter being in the where, it is only going to produce your sum(rent.paid) if the joins work (even though they are left joins)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top