Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 SQL Joining three tables and using LEFT OUTER JOIN

Author  Topic 

dejan88
Starting Member

7 Posts

Posted - 2012-03-19 : 05:30:08
I have three tables and two seperate SQL queries which are working correctly and I am having correct results. If I try to join these three tables I am having null as result.


First query:

select T1.ID,T3.COMPANY
from T1,T3
where (T1.status!='CLOSED') and (T1.PRIORITY)>5 and T1.CLASSID=T3.CLASSID

Second query:

SELECT T1.ID, T2.DESCRIPTION
FROM T1
LEFT OUTER JOIN T2
ON T1.ID=T2.KEY
WHERE T1.status!='CLOSED'
AND (T2.CREATEDATE= (SELECT MAX(CREATEDATE)
FROM T2
WHERE T2.KEY=T1.ID))


I tried to join them but as result I am having null:

select T1.ID,T3.COMPANY,T2.DESCRIPTION
from T1
INNER JOIN T3 ON T1.CLASSID=T3.CLASSID
LEFT OUTER JOIN T2
ON T1.ID=T2.KEY
where (T1.status!='CLOSED') AND (T1.PRIORITY)>5
AND (T2.CREATEDATE= (SELECT MAX(CREATEDATE)
FROM T2
WHERE T2.KEY=T1.ID))


What am I doing wrong? Thanks for help

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2012-03-19 : 07:05:04
You are turning your l;eft join into an inner join in your Where clause, try this instead:


select T1.ID,T3.COMPANY,T2.DESCRIPTION
from T1
INNER JOIN T3
ON T1.CLASSID=T3.CLASSID
AND (T1.status!='CLOSED')
AND (T1.PRIORITY)>5
LEFT OUTER JOIN T2
ON T1.ID=T2.KEY
AND (T2.CREATEDATE= (SELECT MAX(CREATEDATE)
FROM T2
WHERE T2.KEY=T1.ID)
)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-19 : 08:58:56
see

http://weblogs.sqlteam.com/jeffs/archive/2007/05/14/criteria-on-outer-joined-tables.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -