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
 multiple joins returning incorrect results

Author  Topic 

stevenandler
Starting Member

42 Posts

Posted - 2013-01-31 : 16:14:15
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
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-01-31 : 16:30:46
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

52326 Posts

Posted - 2013-02-01 : 02:54:35
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
   

- Advertisement -