Self JOIN का उपयोग
एक self join एक table को खुद से join करता है, इसे दो tables की तरह treat करने के लिए aliases इस्तेमाल करते हुए।
In this page:
Syntax
SELECT a.column, b.column
FROM table_name a
JOIN table_name b ON a.foreign_key = b.id;
Self JOIN
Classic use एक employee table है जिसमें same table में किसी दूसरी row की ओर point करने वाला एक manager_id column है।
Table को दो aliases दें और इन्हें join करें। CEO जैसे बिना manager वाले employees रखने के लिए LEFT JOIN इस्तेमाल करें।
Recursive queries multi-level hierarchies handle करती हैं।
Note:
same table के लिए अलग aliases ही एक self join possible बनाते हैं।
उदाहरण: Self JOIN
CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO staff VALUES (1, 'Ada', NULL), (2, 'Bob', 1), (3, 'Cy', 1), (4, 'Di', 2);
SELECT e.name AS employee, m.name AS manager FROM staff e LEFT JOIN staff m ON e.manager_id = m.id ORDER BY e.id;
-- Output:
-- employee | manager
-- Ada | NULL
-- Bob | Ada
-- Cy | Ada
-- Di | Bob
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- Aliases भूल जाना
- INNER JOIN इस्तेमाल करना और hierarchy का top खोना
- table की दो roles confuse करना
चैप्टर सारांश
- एक table को खुद से join करें
- दो aliases इस्तेमाल करें
- LEFT JOIN top-level rows रखता है
- Recursive CTEs deeper hierarchies करते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: