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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 how to select related columns using different tabl

Author  Topic 

rajnamm1
Starting Member

1 Post

Posted - 2013-04-07 : 03:20:26
In my project I want to select columns from different tables using Tbl1:-

Tbl1 has mem_id,dist_code,city_code
Tbl2 has mem_id,mem_name
Tbl3 has dist_code,dist_name
Tbl4 has city_code,city_name

In Tbl1 either dist_code or city_code will have value >0. Not both will have value >0.

I want to display mem_id,mem_name,dist_name,city_name.

I tried with the following code but coming correct.
Select t.mem_id,m.mem_name,d.dist_name,c.city_name from txfile t join member m on
m.mem_id=t.mem_id join district d on d.dist_code=t.dist_code where t.mem_id=158
join city c on c.city_code=t.city_code where t.mem_id=158

Can anyone help me out?

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-04-07 : 20:58:04
The syntax is not quite right. The correct syntax should be as follows.
Select 
t.mem_id,m.mem_name,d.dist_name,c.city_name
from
txfile t
join member m on
m.mem_id=t.mem_id
join district d on
d.dist_code=t.dist_code
join city c on
c.city_code=t.city_code
where
t.mem_id=158
If you have rows in one table for which there are no corresponding rows in all the other tables, such rows will not be returned via this query. You will need to use one of the outer joins if you do want to return such rows.
Go to Top of Page
   

- Advertisement -