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
 Query to join 3 tables.

Author  Topic 

Sheetalsql
Starting Member

1 Post

Posted - 2013-11-15 : 04:19:40
Hi,
I have 2 tables:

Element(Element_Id, Element_Name) and Parent_Child(Parent_Id, Child_Id). Parent_Id and Child Id are actually the element Ids only. An element can have more than 1 parent or more than one child.

Now i want the output like this:

Element_Id Element_Name Parent_Name Child_Name

Plz help !!

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-11-15 : 05:05:16
Is this?

SELECT p.Element_Id ParentId, p.Element_Name ParentName, c.Element_Id ChildId, c.Element_Name ChildName
FROM Parent_Child pc
LEFT JOiN Element p ON p.Element_Id = pc.Parent_Id
LEFT JOiN Element c ON c.Element_Id = pc.Child_Id

--
Chandu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-11-15 : 06:02:19
quote:
Originally posted by Sheetalsql

Hi,
I have 2 tables:

Element(Element_Id, Element_Name) and Parent_Child(Parent_Id, Child_Id). Parent_Id and Child Id are actually the element Ids only. An element can have more than 1 parent or more than one child.

Now i want the output like this:

Element_Id Element_Name Parent_Name Child_Name

Plz help !!


In such cases how do you want output to display? all parents/child concatenated inside columns in a single row or as different rows with ElemntID and Name repeated?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Rajan Sahai
Starting Member

8 Posts

Posted - 2013-11-23 : 02:21:28
This will explain you very clearly, with Example, visit now
unspammed
Go to Top of Page
   

- Advertisement -