🪞
Joins & Relationships

Self Joins

Joining a Table to Itself
💡 Self, join, EK, "MIRROR" jaisa, hai — EK, HI, TABLE, ko, DO, ALIASES, ke, saath, treat, kiya, jaata hai, JAISE, WOH, DO, ALAG, tables, hon, — hierarchical, ya, self-referencing, data, ke, liye, useful, hai.

Self, join, USEFUL, hai, jab, EK, TABLE, mein, EK, COLUMN, USI, TABLE, ki, DUSRI, row, ko, REFERENCE, karta hai — jaise, employees, table, mein, manager_id, jo, USI, employees, table, ke, EK, dusre, employee, ki, id, hai.

Table, aliases, (jaise, e1, e2) ZAROORI, HAIN, self, joins, mein — MySQL, ko, PATA, honi, CHAHIYE, ki, KAUN, si, "instance" of, the, table, ki, baat, ho, RAHI, hai.

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(100),
  manager_id INT
);

SELECT e1.name AS employee, e2.name AS manager
FROM employees e1
LEFT JOIN employees e2 ON e1.manager_id = e2.id;
🪞
Self, join, EK, "MIRROR" jaisa, hai — EK, HI, TABLE, ko, DO, ALIASES, ke, saath, treat, kiya, jaata hai, JAISE, WOH, DO, ALAG, tables, hon, — hierarchical, ya, self-referencing, data, ke, liye, useful, hai.
1 / 2
⚡ झट से Recap
  • Self join = table, ko, khud, ke, saath, join, karна, (aliases, ke, saath)
  • Hierarchical/self-referencing, data, ke, liye, useful (jaise, manager-employee)
  • Table aliases, ZAROORI, HAIN, self, joins, mein
इस page में (2 subtopics)

Self, join, DUPLICATE, rows, dhoondhne, ke, liye, bhi, use, ho, sakta hai — same, table, ko, khud, se, JOIN, karके, DIFFERENT, id, LEKIN, SAME, values, waali, rows, dhoondhna.

SELECT a.* FROM users a
JOIN users b ON a.email = b.email AND a.id > b.id;
-- Duplicate emails, waali, rows, (later, ones), dikhayi, dengi

Self, join, se, consecutive, rows, (jaise, EK, ORDER, aur, USKA, PREVIOUS, order) ko, COMPARE, kiya, ja, sakta hai — modern, MySQL, mein, LAG()/LEAD(), window, functions, ISKE, liye, CLEANER, solution, HAIN.

💡Tip: MySQL 8.0+ mein, LAG()/LEAD(), window, functions, se, consecutive, row, comparisons, self, joins, se, MUCH, SIMPLER, ho, gaye, HAIN.