Avatar of DHilgarth
DHilgarth asked on

Select from one table twice in one select

Hi,

I have two tables:
Table 1 with 3 Columns: ID, ID_Source, ID_Target
Table 2 with 2 Columns: ID, Name

Now I want a select that returns the ID from Table 1 and the Names for Source and Target.
Microsoft SQL Server 2005SQL

Avatar of undefined
Last Comment
Mark Wills

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Guy Hengel [angelIII / a3]

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Guy Hengel [angelIII / a3]

if id_source and/or id_target could be null, use LEFT JOIN instead of JOIN
Pratima

Select T1.ID , T2.Name as SourceName ,T3.Name as TargetName    from Table 1 T1 , Table 2 T2 ,Table T3
where T1.ID_Source = T2.ID  and T1.ID_Target = T3.ID
dngfng

Try it with this:
SELECT T1.ID, (SELECT NAME FROM TABLE2 AS T2  WHERE T1.ID_Source = T2.ID) AS SOURCE, (SELECT NAME FROM TABLE2 AS T2 WHERE T1ID_Target = T2.ID)
FROM TABLE1 AS T1

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
thew00d

Here's my attempt
SELECT t.ID, t1.Name as Source, t2.Name as Target
FROM table1 t
LEFT JOIN NamesTable t1 on t.ID_Source = t1.ID
LEFT JOIN NamesTable t2 on t.ID_Target = t2.ID

Open in new window

SOLUTION
Mark Wills

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
DHilgarth

Thanks all. It works. The first answer was the right one. Along with all the other similar ones ;-)
How is it handled here with the points in such a case? First come first served? Or should I split them evenly?
Mark Wills

typially award the one that you used as the answer, and if any other postings helped you, then you can divvy up some "assisted" points.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.