Reputation: 20346
I have a simple sql question here, I see some queries like this:
SELECT
users.id, users.username, users.password
FROM
users AS User
LEFT JOIN
users AS User0 ON ...
LEFT JOIN
users AS User1 ON ...
LEFT JOIN
users AS User2 ON ...
WHERE
...
ORDER BY ... DESC
In which, as you can see above, the same table users
is being left-joined 3 times. My question is this, why would somebody wanna join a table on itself? What exactly is the purpose of doing something like that?
Please give me the best explanation with clear examples if possible
Thank you
Upvotes: 4
Views: 2963
Reputation: 1898
If you have a hierarchical relationship you may join a table to itself, here is an example schema and query:
CREATE TABLE category (
id int NOT NULL auto_increment,
primary key(id),
category_name varchar(64) NOT NULL,
parent_category_id int DEFAULT NULL,
foreign key(parent_category_id) references category(id)
) engine=innodb;
Let's say you have a store that has various categories that products can be in. Let's say in this example you're browsing through categories and you would like to display all categories under their parent category:
SELECT parent_category.id AS parent_category_id,
parent_category.category_name AS parent_category_name,
child_category.id AS category_id,
child_category.category_name AS category_name
FROM
category AS parent_category
LEFT OUTER JOIN category AS child_category ON child_category.parent_category_id = parent_category.id;
In this case you would get all child categories with their info about parent categories. This pattern is often used to store hierarchical structures in a relational database.
Upvotes: 1
Reputation: 3368
Suppose you want to track users, as well as who referred them to your site. You might design a table for storing users like this:
create table users (
id int unsigned primary key auto_increment,
name varchar(100),
...
referredby int unsigned
);
If you then wanted to view both the user and who referred them, you would need to join the referredby column of the user to the id column of the person who referred them. i.e.:
SELECT u.name user, r.name referrer
FROM users u LEFT JOIN users r ON u.referredby = r.id
So that's why you'd do it.
Upvotes: 3
Reputation: 499002
This is normally done when you have a hierarchy.
Say a table of employees where each employee has a manager - the manager is signified with a ManagerId
field that is the managers' employee ID.
If you want to see each employee, their manager, the managers' manager etc, self joins would be the way to write the query.
Upvotes: 4