Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys

I need some assistance with the below

I have 3 database tables

A
B
C

Table A and Table B have a 1 to many relationship(Key_Table A = Multiple in Table B)
Table A and Table C also have a 1 to many relationship(Key_Table A = Multiple in Table C)

The problem i am facing is that i need to write a query to retrieve some information from Table A,B,C
for eg.

Select Column1,column2,TableB.column1,TableC.column1
from Table A

How would i join these tables so that i wont get a duplication of records?

What I have tried:

Select TableA.Column1,TableB.Column1,TableC.Column1

From TableA
Inner Join
TableB on TableA.Column_key = TableB.TableA_key
Inner Join
TableB on TableA.Column_key = TableB.TableA_key
Posted
Updated 16-Apr-16 8:46am
Comments
ZurdoDev 14-Apr-16 9:12am    
Join both tables and you can use SELECT DISTINCT if you are getting duplicates.
IsiR_19 14-Apr-16 10:07am    
The problem i am having is when i join the tables i am getting the following result e.g

Table A Key = 1

Table B Column1 = 15 where TableB.TableA_key = 1
Table B Column1 = 20 where TableB.TableA_key = 1

Table C Column1 = 10 where TableB.TableA_key = 1
Table C Column1 = 11 where TableB.TableA_key = 1

Result will bring Back

Result 1
Key = 1
TableB.column1 = 15
TableC.column1 = 10

Result 2
Key = 1
TableB.column1 = 20
TableC.column1 = 10

Result 3
Key = 1
TableB.column1 = 15
TableC.column1 = 11

Result 4
Key = 1
TableB.column1 = 20
TableC.column1 = 11

i only require 2 sets of results


Result 3
Key = 1
TableB.column1 = 15
TableC.column1 = 11

Result 4
Key = 1
TableB.column1 = 20
TableC.column1 = 11
ZurdoDev 14-Apr-16 10:08am    
I don't follow.
F-ES Sitecore 14-Apr-16 10:28am    
The easiest way of dealing with this is normally just getting all the results, including the duplicate data you don't need, and forming a data structure more like what you want in your code. SQL doesn't really do hierarchical data which is what I suspect you are looking for. Well, you can use xml, but good luck with that.

1 solution

So you only want resulting rows from one of the rows in TableC, then you must add a condition for that.
SQL
WITH CTE AS (
    SELECT  TableA.KEY
           ,Max(TableC.Column1) AS Column1
    FROM    TableA
    JOIN    TableC ON TableA.Column_key = TableC.TableA_key
    GROUP BY TableA.KEY
    )
SELECT  CTE.KEY
       ,TableB.Column1
       ,CTE.Column1
FROM    CTE
JOIN    TableB ON CTE.KEY = TableB.TableA_key
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900