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
 Simple query

Author  Topic 

salmoliv
Starting Member

2 Posts

Posted - 2010-08-23 : 10:58:05
I have a table recording changes, with few fields

CHANGES
- ID
- FROM
- TO

The FROM and TO fields contains IDs pointing to a different table, STATES.

STATES
- ID
- NAME

I would like to have a query returning all my changes with the state name instead of the state ids

So, if I have in my CHANGES table and in My STATES tables the followings:
CHANGES
0 0 1
1 0 2

STATES
0 New
1 Closed
2 Returned

I would like the query to return:
0 New Closed
1 New Returned

Thank you

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2010-08-23 : 11:07:12
select c.id, s1.name, s2.name
from Changes as c
left join states as s1 on s2.id = c.from
left join states as s2 on s2.id = c.to



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

salmoliv
Starting Member

2 Posts

Posted - 2010-08-23 : 17:02:57
Thank you,

I think the correct query should be:

select c.id, s1.name, s2.name
from Changes as c
left join states as s1 on s1.id = c.from
left join states as s2 on s2.id = c.to
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-24 : 07:22:14
why do you need LEFT JOIN? I think seeing your sample data INNER JOIN is enough

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

Go to Top of Page
   

- Advertisement -