Translate

Wednesday, 19 August 2015

What is Self Joins ?

In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:


class Employee < ActiveRecord::Base
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"
 
  belongs_to :manager, class_name: "Employee"
end


In database management systems, a self-join is a query that joins a table to itself. This means that the same table is used twice in the join operation, but with different aliases to distinguish between the two copies.

Self-joins are typically used when we need to find relationships between rows within the same table. For example, consider a table that contains information about employees in a company. Each employee record may have a supervisor_id column, which contains the ID of that employee's supervisor. To find the name of an employee's supervisor, we can use a self-join to join the table to itself on the supervisor_id column.

Here is an example SQL query for a self-join:


SELECT e1.name AS employee_name, e2.name AS supervisor_name
FROM employees e1
JOIN employees e2 ON e1.supervisor_id = e2.id;

In this query, we are joining the employees table to itself, using the aliases e1 and e2 to distinguish between the two copies. We are selecting the name of each employee (using e1.name) and the name of their supervisor (using e2.name), where the supervisor_id column in the first copy of the table (e1) matches the id column in the second copy (e2)

2 comments:

  1. nice https://www.awrtechnologies.com

    ReplyDelete
  2. nice https://www.awrtechnologies.com

    ReplyDelete