LEFT JOIN का उपयोग
LEFT JOIN left table से हर row रखता है और जब कोई match न हो right side को NULL से भरता है।
In this page:
Syntax
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.key = table2.key;
LEFT JOIN
सारे customers list करने के लिए इसे इस्तेमाल करें भले ही उनके कोई orders न हों। WHERE में right-table column पर filter करना इसे वापस एक inner join में बदल देता है, इसलिए ऐसी conditions ON में रखें।
एक common trick है LEFT JOIN plus WHERE right.id IS NULL partner न रखने वाली rows ढूंढने के लिए।
Note:
IS NULL के साथ LEFT JOIN वे rows ढूंढता है जिनका कोई match नहीं।
उदाहरण: LEFT JOIN
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, total INTEGER);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Bob'), (3, 'Cy');
INSERT INTO orders VALUES (10, 1, 50), (11, 1, 20), (12, 2, 75);
SELECT c.name, o.total FROM customers c LEFT JOIN orders o ON o.customer_id = c.id ORDER BY c.id, o.id;
SELECT c.name AS never_ordered FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;
-- Output:
-- name | total
-- Ada | 50
-- Ada | 20
-- Bob | 75
-- Cy | NULL
-- never_ordered
-- Cy
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. #}
आम गलतियां
- WHERE में right table filter करना
- यह मान लेना कि NULLs मतलब join fail हुआ
- left और right tables confuse करना
चैप्टर सारांश
- LEFT JOIN सारी left rows रखता है
- Unmatched right columns NULL हैं
- ON में right tables filter करें
- IS NULL unmatched rows ढूंढता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: