Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join return rows when Where not satisfied

I have a table of Monkeys and a table of Trees with a many-to-many relationship joined by a third MonkeysTrees FK Table.

I have this query that returns all the Monkeys and Trees for a given Tree Id:

SELECT * 
FROM Monkeys m
JOIN MonkeysTrees mt ON mt.MonkeyId = m.Id
join Trees t ON t.Id=mt.TreeId
WHERE t.Id = 1;

If I change t.Id in the final WHERE clause to an Id that isn't in the Trees table, I'd still like to return a table containing all the Monkeys, but with NULL in the joined fields. How could I do that?

like image 917
Will Jenkins Avatar asked Dec 05 '25 15:12

Will Jenkins


1 Answers

You can use an outer join, the position of the on clauses below yields Monkeys left join (MonkeysTrees inner join Trees where treeid = 1)

SELECT * 
FROM Monkeys m
LEFT JOIN MonkeysTrees mt
           INNER JOIN Trees t ON t.Id=mt.TreeId AND t.Id = 1
ON mt.MonkeyId = m.Id
like image 99
Martin Smith Avatar answered Dec 07 '25 06:12

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!