SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 multiple joins returning incorrect results
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

stevenandler
Starting Member

USA
42 Posts

Posted - 01/31/2013 :  16:14:15  Show Profile  Reply with Quote
I am attemping to create a transact sql statement which will perform multiple joins here is the code:

SELECT A.RESULT_KEY,B.LINE_CNT FROM OPTC.RES_M_LAB A INNER JOIN OPTC.RES_D_OBX_LAB B
ON A.RESULT_KEY = B.RESULT_KEY
WHERE B.RESULT_KEY = 79
ORDER BY B.LINE_CNT

When I run the above statement, I get 2 rows back which is correct because the table OPTC.RES_D_OBR_LAB has 2 rows meeting the criteria.

However, if I attempt to use multiple joins as in the following example:

SELECT A.RESULT_KEY,B.LINE_CNT FROM OPTC.RES_M_LAB A INNER JOIN OPTC.RES_D_OBR_LAB B
ON A.RESULT_KEY = B.RESULT_KEY
INNER JOIN OPTC.RES_D_OBX_LAB C
ON A.RESULT_KEY = C.RESULT_KEY
WHERE B.RESULT_KEY = 79
ORDER BY B.LINE_CNT

I am getting back 78 rows. I know this is incorrect because table OPTC.RES_D_OBX_LAB has 39 rows meeting the criteria. It appears that
I am getting back a cartesian result even though I specify an inner join both times in my statement.

Can someone please shed some light on this for me and tell me how to modify this statement so I get back 41 rows instead on 78.

James K
Flowing Fount of Yak Knowledge

3744 Posts

Posted - 01/31/2013 :  16:30:46  Show Profile  Reply with Quote
That is possible - see this example - I have two tables, one with three rows, the other with two. When I do an inner join, I get six rows back. For each row in the left table, one row for each match in the right table is returned in the result set.

Perhaps you need to join on more columns?
CREATE TABLE #A(n INT);
CREATE TABLE #B(m INT);
INSERT INTO #A VALUES (1),(1),(1);
INSERT INTO #B VALUES (1),(1);

SELECT * FROM #A INNER JOIN #B ON #A.n = #B.m;

DROP TABLE #A, #B;
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 02/01/2013 :  02:54:35  Show Profile  Reply with Quote
the join condition you're giving currently doesnt reflect the actual columns on which tables are related. Thats why its matching on more records than what it actually should and giving you bigger result.

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

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000