Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left Outer join and an additional where clause

Tags:

sql

join

I have a join on two tables defined as a left outer join so that all records are returned from the left hand table even if they don't have a record in the right hand table. However I also need to include a where clause on a field from the right-hand table, but.... I still want a row from the left-hand table to be returned for each record in the left-hand table even if the condition in the where clause isn't met. Is there a way of doing this?

like image 375
atamata Avatar asked Sep 09 '10 13:09

atamata


People also ask

Can we use WHERE clause in left outer join?

An outer join returns all of the rows that the equivalent inner join would return, plus non-matching rows from one or both tables. In the FROM clause, you can specify left, right, and full outer joins. In the WHERE clause, you can specify left and right outer joins only.

Can we use join and WHERE clause together?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

What is the difference between left join with WHERE clause & left join with WHERE clause?

When you use a Left Outer join without an On or Where clause, there is no difference between the On and Where clause. Both produce the same result as in the following. First we see the result of the left join using neither an On nor a Where clause.

Can you put a WHERE clause before a join?

The where clause will be executed before the join so that it doesn't join unnecessary records.


2 Answers

Yes, put the condition (called a predicate) in the join conditions

   Select [stuff]    From TableA a        Left Join TableB b            On b.Pk = a.Pk                -- [Put your condition here, like this]                And b.Column = somevalue 

The reason this works is because the query processor applies conditions in a where clause after all joins are completed, and the final result set has been constructed. So, at that point, a column from the a table on the outer side of a join that has null in a a column you have established a predicate on will be excluded.

Predicates in a join clause are applied before the two result sets are "joined". At this point all the rows on both sides of the join are still there, so the predicate is effective.

like image 115
Charles Bretana Avatar answered Sep 21 '22 22:09

Charles Bretana


You just need to put the predicate into the JOIN condition. Putting it into the WHERE clause would effectively convert your query to an inner join.

For Example:

... From a Left Join b on a.id = b.id and b.condition = 'x' 
like image 41
Martin Smith Avatar answered Sep 22 '22 22:09

Martin Smith