954,566 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Joins

Hi
can any one help me in following case?
Table A

ID | Name
1 , Apple
2 , Bat
3 , Cat
4 , Dog

Table B
ID | Name

1 , A
2 , B
3 , C
4 , D
5 , E
6 , F
7 , G

How will i get the below result??

Results

ID | Name

1 , Apple
2 , Bat
3 , Cat
4 , Dog
5 , E
6 , F
7 , G
How can I achieve this.
Thanks

bhakti.thakkar
Newbie Poster
14 posts since Sep 2007
Reputation Points: 10
Solved Threads: 1
 

ok, i am assuming that you want a name for all id's. if a has an entry use that, otherwise use the name from b. also assuming that B has an entry for every id. if those assumptions are correct, then this should work

select b.id, isnull(a.name,b.name) as [Name] from b
left join a on b.id = a.id
campkev
Posting Pro in Training
484 posts since Jul 2005
Reputation Points: 14
Solved Threads: 19
 

Or maybe:

select b.id, isnull(a.name,b.name) as [Name] from b
left join a on b.[Name] = LEFT(a.[Name],1)
hollystyles
Veteran Poster
1,182 posts since Feb 2005
Reputation Points: 262
Solved Threads: 68
 

that would add the assumption that the names in b are the first letter of the names in a

campkev
Posting Pro in Training
484 posts since Jul 2005
Reputation Points: 14
Solved Threads: 19
 

Hmm not really, it replaces the assumption that a.id is a foreign key to b.id.

The OP does not specify. If there is a relation between the id's (which there should be in my opinion, and if the data provided represents all possibilities, then this is indeed the case) your solution is the more efficient.

However if the id's are not related then that only leaves the initial letters, in which case my alternate solution will do.

hollystyles
Veteran Poster
1,182 posts since Feb 2005
Reputation Points: 262
Solved Threads: 68
 

ok, i am assuming that you want a name for all id's. if a has an entry use that, otherwise use the name from b. also assuming that B has an entry for every id. if those assumptions are correct, then this should work

select b.id, isnull(a.name,b.name) as [Name] from b
left join a on b.id = a.id


Thanks to reply my query. It worked. :)

bhakti.thakkar
Newbie Poster
14 posts since Sep 2007
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You