Click here to Skip to main content
14,929,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need a query to get values from two table as shown below. Please somebody help me on the same.

HTML
City table is below
tblLocation 
Id   CityName
1    Bangalore
2    Mysore
3    Hassan
4    Chennai
5    Hyderabad

Route table is below
tblRoute   
Id  SourcePlace DestinationPlace
1   1           2
2   3           4
3   5           1
4   3           4
5   5           1
6   2           4

Result table is below
RouteId  SOurcePlace    DestinationPlace
1        Bangalore      Mysore
2        Hassan         Chennai
3        Hyderabad      Bangalore
4        Hassan         Chennai
5        Hyderabad      Bangalore
6        Mysore         Chennai


The query I tried to get above Result table is as below

SQL
select r.Id as RouteId,
(select CityName from tblLocation where ID=r.SourcePlace) as SourcePlace,
(select CityName from tblLocation where ID=r.DestinationPlace) as DestinationPlace
 from tblRoute


Above query performance is less. So please provide query which performance good. Also don't use inner queries like above.

Thanks in advance.. :-)
Posted

You must JOIN the tblLocation table two times. That looks something like
SQL
SELECT tblRoute.Id as RouteId, a.Cityname as SourcePlace, b.Cityname as DestinationPlace
FROM tblRoute
INNER JOIN tblCity a ON tblRoute.SourcePlace=a.Id
INNER JOIN tblCity b ON tblRoute.DestinationPlace=b.Id
   
Comments
Mahesh Pandekar 28-Mar-14 7:25am
   
Error: Msg 208, Level 16, State 1, Line 1
Invalid object name 'tblCity'.

Updated => SELECT a.Id as RouteId, b.Cityname as SourcePlace, c.Cityname as DestinationPlace
from tblRoute a inner join tblLocation b on a.SourcePlace = b.Id
left outer join tblLocation c on a.DestinationPlace = c.Id
-- Inner join also works fine
SQL
SELECT a.Id as RouteId, b.Cityname as SourcePlace, c.Cityname as DestinationPlace
from tblRoute a inner join tblLocation b on a.SourcePlace = b.Id
left outer join tblLocation c on a.DestinationPlace = c.Id


Tested it on SQL Server - 2008 R2, It works fine.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900