Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain Self Join

Tags:

join

mysql

I have tried to understand self-join studying on the Internet, but couldn't find satisfactory explanation. can anybody please explain it with an example like where to use it and why to use it? would be nice if you can explain it with query.

like image 369
Vandan Patel Avatar asked Feb 02 '26 15:02

Vandan Patel


2 Answers

Wikipedia's Join (SQL) page has a specific entry about self-join, including an example.

As another example, suppose you had a Person table with columns of Id and ParentId to indicate parentage, you might do something like:

SELECT parent.Name, child.Name
FROM Person parent
INNER JOIN Person child ON parent.Id = child.ParentId
like image 128
Jon Skeet Avatar answered Feb 05 '26 07:02

Jon Skeet


Reasons for using a self join me be a hierarchy.

E.g.: You have all employees in a table. Every employee has a manager. So you can link an employee with his manager.

Table emp (loyee). cols emp_id, manager, name

so you could get all employees together with the name of the manager

select e.name employeename, m.name managername 
from emp e, emp m where e.manager = m.emp_id
like image 35
Udo Held Avatar answered Feb 05 '26 09:02

Udo Held



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!