Click here to Skip to main content
15,921,382 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hello guys...

can you guys help me with this problem ?
the problems
i have two table that related to each other twice
so they may come two times in same rows for example
the related value may be in first rows 1 and in second rows 2
but when im joining them both comes with same value (1)
and that's wrong ,,
im sorry if i couldn't explain well :(
i created this example that's show exactly my problems.

SQL
 tblcity
+---------+------------+
| ID      | NAME       | 
+---------+------------+
|1        | paris      |
|2        | munchen    |
|3        | Berlin     |
+---------+------------+
tblmv
--this table is realted with tblcity twice once with from_city second to_city   
+---------+------------+-----------+--------+--------+
| ID      | NAME       |from_city  |to_city |status  |
+---------+------------+-----------+--------+--------+
| 1       | JAmes      | 1         |  2     |arrive  |
| 2       | Alex       | 2         |  3     |depart  |
+---------+------------+-----------+--------+--------+
view table be like 
+---------+------------+-----------+--------+-------+
| ID      | NAME       |from_city  |to_city |status |
+---------+------------+-----------+--------+-------+
| 1       | JAmes      | paris     |munchen |arrive |
| 2       | Alex       | munchen   |Berlin  |depart |
+---------+------------+-----------+--------+-------+

any kind of help will be so appreciated

What I have tried:

i tried with all joins way inner join left join right joins
Posted
Updated 22-Aug-16 12:38pm

1 solution

To get the results you need, you need to join the tblCity table twice. Once for the From_City value and again for the To_City value.

What you end up with is something like

SQL
SELECT        dbo.tblmv.ID, dbo.tblmv.Name, dbo.tblmv.Status, tblCity_1.name AS from_City, dbo.tblCity.name AS To_City
FROM            dbo.tblCity INNER JOIN
                         dbo.tblmv ON dbo.tblCity.ID = dbo.tblmv.From_City INNER JOIN
                         dbo.tblCity AS tblCity_1 ON dbo.tblmv.To_City = tblCity_1.ID

which gives you results of


ID Name Status from_City To_City
1 James arrive Munchen Paris
2 Alex Depart Berlin Munchen
 
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