Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL where clause for left outer join

I have a problem with a view I want to create. I have two tables joined in a left outer join, say tableA and tableB, where tableB is left outer joined.

I want to select only those rows from table B where state equals 4, so I add WHERE state = 4 to my query. Now the result set is trimmed quite a bit because all rows without a matching row in tableB are removed from the result (since state isn't 4 for those rows). I also tried WHERE state = 4 OR state IS NULL, doesn't work either (since state technically isn't NULL when there is no state).

So what I need is a WHERE statement which is only evaluated when there actually is a row, does such a thing exist?

If not I see two options: join (SELECT * FROM tableB WHERE state = 4) instead of table B, or create a view with the same WHERE statement and join that instead. What's the best option performance wise?

This is SQL Server 2008 R2 by the way.

like image 644
Jasper Avatar asked Aug 24 '11 07:08

Jasper


People also ask

Can we use WHERE clause in joins?

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.

How can I check left outer join?

Left Outer Join: Left Outer Join returns all the rows from the table on the left and columns of the table on the right is null padded. Left Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the left table. SELECT [column1, column2, ....]

What is the correct query for left outer join?

SQL left outer join is also known as SQL left join. Suppose, we want to join two tables: A and B. SQL left outer join returns all rows in the left table (A) and all the matching rows found in the right table (B). It means the result of the SQL left join always contains the rows in the left table.

WHERE vs left outer join?

There really is no difference between a LEFT JOIN and a LEFT OUTER JOIN. Both versions of the syntax will produce the exact same result in PL/SQL. Some people do recommend including outer in a LEFT JOIN clause so it's clear that you're creating an outer join, but that's entirely optional.


2 Answers

You put the conditions in the on clause. Example:

select a.this, b.that
from TableA a
left join TableB b on b.id = a.id and b.State = 4
like image 180
Guffa Avatar answered Nov 15 '22 13:11

Guffa


You can add state = 4 to the join condition.

select * 
from T1
  left outer join T2
    on T1.T1ID = T2.T1ID and
       T2.state = 4
like image 22
Mikael Eriksson Avatar answered Nov 15 '22 13:11

Mikael Eriksson