Click here to Skip to main content
15,914,608 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I create table

SQL
create table mytable1
(
  id int,
  name varchar(20),
  mid varchar(20)
)


SQL
insert into mytable1 values(1,'A',Null)
insert into mytable1 values(2,'B',1)
insert into mytable1 values(3,'C',Null)
insert into mytable1 values(4,'D',1)


id name mid
===========
1   A    null
2   B     1
3   C    null
4   D     1

I need to write the query using self join to get the following output

VB
 name mid
===========
  A    null
  B     A
  C    null
  D     A
Posted
Updated 13-Jan-13 19:52pm
v2

SQL
Select
X.name,Y.name as name
From mytable1 X
Left Join mytable1 Y on (X.id = Y.mid)
 
Share this answer
 
try this

SQL
SELECT a.name, B.name as mid FROM mytable1 A
LEFT OUTER JOIN
(SELECT Id,name FROM mytable1 WHERE mid is null)  B
ON A.mid=B.id
 
Share this answer
 
v2
since you pass mid as integer values if you change your data type of mid to int, query execution will be faster.
following sample is based on mid as int
SQL
select e.name as Name,m.name as MID from mytable1 as e
left outer join mytable1 as
m on m.id = e.mid;
 
Share this answer
 
Comments
Basheer Belgod 14-Jan-13 2:28am    
Thank you :) its working fine but the requirement is have to use the self join
instead of left outer join
Jibesh 14-Jan-13 2:36am    
was this a homework? whether the answer is yes or no you should start reading some sql basics before you go further. The term 'self join' means table which joins self, there is no such keyword SELF JOIN like LEFT/RIGHT join.

SQL Joins tutorialsLink will help you to understand more about SQL Joins.
[no name] 14-Jan-13 9:14am    
Yes I agree to jibesh. Please use once to your own knowledge using google. Google is the best friend indeed... :D

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