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.
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.
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, ....]
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With