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)
 SQL - joining

Author  Topic 

code4life
Starting Member

1 Post

Posted - 2010-04-29 : 15:52:13
Hello All:

I am running into a little bit of a wall in writing a SQL query. Here is an example.
I have 4 tables: TABLE1, TABLE2, TABLE3, TABLE4
TABLE1 is a general table in which it has Address information relating to TABLE2, TABLE3, and TABLE4
TABLE2 is a table of customers
TABLE3 is a table of leads
TABLE4 is a table of vendors

TABLE1 has a PK called 'ID' which is a foreign key in TABLE2, TABLE3, and TABLE4

What I need to do is return all the ID's from TABLE1 and all of the company information from the relevant table either TABLE2, TABLE3, or TABLE4.

The TABLE1 'ID' will only represent 1 record in either TABLE2, TABLE3, or TABLE4 and I do not know which table it belongs to.

Here is my code so far:
select * from TABLE1
left outer join TABLE2 on TABLE1.Id = TABLE2.aId
left outer join TABLE3 on TABLE1.Id = TABLE3.aId
left outer join TABLE4 on TABLE1.Id = TABLE4.aId


The code executes and returns results. However, I do not want to: Select *
TABLE2 has a column called CNAME
TABLE3 has a column called LNAME
TABLE4 has a column called VNAME

I would like to return the name as COMPANYNAME. The name will be from one of those columns.

Any help with this would be greatly appreciated.

Also, I am not able to change the design of the tables.

Thank You.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-29 : 16:27:59
You should union Table2-4 together to form one table:

select dt.COMPANYNAME, TABLE1.id
from TABLE1
left join (select aid, companyname from TABLE2 union select aid, companyname from TABLE3 union select aid, companyname from TABLE4) dt
on TABLE1.Id = dt.aId


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -