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.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2006-05-10 : 08:07:08
|
| Prathiba writes "i have a table named loc_statewith the following columns StateId StateNamei have another table car_journey with the following columns OriginsateIddesstateid etc now i want origin statename and destination statename by comparing stateid with originsttateid and at the same time stateid with destination stateidwhat should i do " |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
druer
Constraint Violating Yak Guru
314 Posts |
Posted - 2006-05-10 : 17:14:37
|
| Based on the way I see the table design there are a couple of things to keep in mind:1. There could be more than 1 DESTSTATEID for any particular ORIGINSTATEID. If there weren't then it wouldn't make sense to have the DESTSTATEID field in a seperate table.2. There could be an ORIGINSTATEID that doesn't have a corresponding DESTSTATEID field. (You'll notice in both samples below that in order to get the State Names you'll have to refer to the StateTable two times so you have to ALIAS that table. In the sample I alias the table as ST1 and ST2, where ST1 is for the originating state name, and ST2 is for the destination state name)You have to consider all of the factors about the data, and answer some other questions when you determine which type of JOIN you are going to perform. If you use an INNER JOIN as suggested then you will only see the ORIGINSTATEID's that do have at least 1 match. But will NOT see any ORIGINSTATEID's that don't have an entry for DESTSTATEID.Select ST1.StateName, ST2.StateNamefrom StateTable ST1 INNER JOIN DestTable on DestTable.OriginStateId = ST1.StateIdINNER JOIN StateTable ST2 on ST2.StateId = DestTable.DestStateIdYou can alternatively use what is referred to as an OUTER JOIN if you really do want to see all of the originating states whether they have a match or not. If you use the following you will simply get the value NULL for the DestStateId if the match can't be found:Select ST1.StateName, ST2.StateNamefrom StateTable ST1 OUTER JOIN DestTable on DestTable.OriginStateId = ST1.StateIdINNER JOIN StateTable ST2 on ST2.StateId = DestTable.DestStateIdHope it helps,DaltonBlessings aren't so much a matter of "if they come" but "are you noticing them." |
 |
|
|
|
|
|