tags:

views:

49

answers:

4

Hello guys, consider the following example. alt text

I have to select all the records from table1 which exist in table2 also + all the records from table2 which don't exist in table1 but exist in table2 and have IsActive=1 and status not null.

I initially tried it with a join but how to do the later part where I have to select the records which don't exist in table 1 ? I have to do it inside a single query presumably with a SQL view.

Edit Guys I need to combine the results like a UNION of 2 tables, so incase of rows absent in table1 but present in table2, the columns of belonging to table1 would be blank.

+2  A: 

Here's an example query:

select  *
from    Table2 t2
left join
        Table1 t1
on      t1.id = t2.id
where   t1.id is not null
        or (isActive = 1 and status is not null)

The first line of the where clause takes care of "all the records from table1 which exist in table2". The second line is for "don't exist in table1 but exist in table2 and have IsActive=1 and status not null".

Andomar
thanks Andomar, can you take a look at my query ? Its not working although I tried similar as you. Also, why did you used an OR instead of AND? Also table1 is joined over table2. Any reason ?
Popo
@Popo: You'd have to clarify "not working". The OR is to show rows that meet at least one condition; with AND, they'd have to meet all conditions. I'm starting with Table2 because you'd like to show rows from Table2 even though there is no matching row in Table1.
Andomar
Hi, with my previous query I am getting columns from only 1 table and null columns from table 2. Also I cant get your query to work
Popo
I am getting only records from table2 and none from table1.
Popo
Hey Andomar, the join is converted to an inner join.
Popo
+2  A: 

You will need an outer join here.

http://msdn.microsoft.com/en-us/library/ms187518.aspx

Scott Munro
A: 

Is this it? Not sure if I got right what you want to do.

SELECT
    *
FROM
    Table1 t1
        JOIN
    Table2 t2 ON (t1.ID = t2.ID OR (t1.ID IS NULL AND t2.isActive = 1 AND t2.Status IS NOT NULL))
Kaltas
A: 

it seems like outer join with where is becoming an inner join.

Popo