0

Is there any way that I can join a table with the same table?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Giri Prasad
  • 1,175
  • 2
  • 8
  • 13

4 Answers4

3

This is known as Self Join.

Quoting w3resource.com,

A self join is a join in which a table is joined with itself (which is also called Unary relationships), specially when the table has a FOREIGN KEY which references its own PRIMARY KEY. To join a table itself means that each row of the table is combined with itself and with every other row of the table.

The self join can be viewed as a join of two copies of the same table. The table is not actually copied, but SQL performs the command as though it were.

A typical example:

SELECT  a.ID, b.NAME, a.SALARY 
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;
Community
  • 1
  • 1
shauryachats
  • 9,975
  • 4
  • 35
  • 48
1

You can use the self join.

An example to explain the self join. Lets say you have a table which have Employee and Supervisor details like this:

EmployeeName      SupervisorName
ABC                XYZ
DEF                YZX
PQR                XYZ
HJK                PQR

Now if I want to find who all employee have the same Supervisor as employee ABC.

So possible approach:

Approach 1

SELECT employeename
FROM employee
WHERE SupervisorName = "ABC"

So for this we need to have the name of the Supervisor for which we want to get the details(An absurd one)

Approach 2:

SELECT employeename
FROM employee
WHERE SupervisorName in
( SELECT SupervisorName 
FROM employee
WHERE employee_name = "ABC")

This one is not as efficient as using the Self Join

Approach 3:- Using the Self Join

SELECT e1.employeename
FROM employee e1 self join employee e2
on e1.SupervisorName  = e2.SupervisorName 
AND e2.employeename="ABC";
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Yes, if you set an alias to the table

... from my_table join my_table as 'othertable' ON ...

Dani
  • 161
  • 4
0

Following link describes self join in sql server : https://technet.microsoft.com/en-us/library/ms177490%28v=sql.105%29.aspx

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45