15. INNER JOIN आणि LEFT JOIN (आधी लागणारे दोन joins)
15.2 LEFT JOIN काय ठेवतं (डावीकडचा प्रत्येक row, जुळो वा न जुळो)
का (Why). Reports मध्ये बऱ्याचदा प्रत्येक shipment किंवा प्रत्येक customer दिसायला हवा, problem असलेले सुद्धा. LEFT JOIN ते ठेवतो, त्यामुळे problems दिसत राहतात.
काय (What). LEFT JOIN डावीकडच्या table चा, म्हणजे FROM नंतर लिहिलेल्या table चा, प्रत्येक row ठेवतो. Match असेल तर उजवीकडच्या table चे columns जोडतो. Match नसेल तर उजवीकडच्या table चे columns NULL ने भरतो. म्हणून LEFT JOIN नंतरचा NULL म्हणजे match नाही असं असू शकतं, किंवा उजवीकडच्या table मध्ये साठवलेला खरा NULL असू शकतो. फरक ओळखायला h.hub_id सारखा उजवीकडच्या table चा key column तपासा.
कसं (How). तोच shipment–hub join LEFT JOIN म्हणून चालवा, मग प्रत्येक customer च्या shipments मोजा, एकही नसलेल्या customer सकट.
पायऱ्या
- पहिलं उदाहरण run करा आणि सगळ्या 10 shipments बघा.
- 1009 आणि 1010 शोधा: match नव्हता म्हणून त्यांचे hub columns NULL आहेत.
- दुसरं उदाहरण run करा आणि 0 shipments सोबत Marina Spices बघा.
- जुळणाऱ्या shipments मोजायला उजवीकडच्या table चा primary key, s.shipment_id, मोजा, कारण खऱ्या match मध्ये तो कधीच NULL नसतो. COUNT(*) Marina साठी 1 देईल, कारण तो result rows मोजतो, match नसलेल्या placeholder row सकट.
उदाहरणे
उदाहरण 1 · dataset: swiftship_logistics
SELECT s.shipment_id, s.hub_id, h.hub_id AS matched_hub, h.hub_code
FROM shipments AS s
LEFT JOIN hubs AS h ON h.hub_id = s.hub_id
ORDER BY s.shipment_id;Output
| shipment_id | hub_id | matched_hub | hub_code |
|---|---|---|---|
| 1001 | 1 | 1 | PNQ-01 |
| 1002 | 1 | 1 | PNQ-01 |
| 1003 | 2 | 2 | BOM-02 |
| 1004 | 3 | 3 | DXB-01 |
| 1005 | 3 | 3 | DXB-01 |
| 1006 | 4 | 4 | LHR-03 |
| 1007 | 1 | 1 | PNQ-01 |
| 1008 | 2 | 2 | BOM-02 |
| 1009 | 9 | NULL | NULL |
| 1010 | NULL | NULL | NULL |
Meaning. सगळ्या 10 shipments राहतात. 1009 आणि 1010 साठी matched_hub आणि hub_code NULL आहेत कारण कुठलाच hub जुळला नाही. हे NULL join ने बनवले, hubs मध्ये साठवलेले नाहीत.
उदाहरण 2 · dataset: swiftship_logistics
SELECT c.customer_name,
COUNT(s.shipment_id) AS shipments
FROM customers AS c
LEFT JOIN shipments AS s ON s.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_name
ORDER BY c.customer_id;Output
| customer_name | shipments |
|---|---|
| Kavya Traders | 2 |
| Desai Pharma | 2 |
| Al Noor Foods | 2 |
| Thames Books | 2 |
| Lotus Crafts | 2 |
| Marina Spices | 0 |
Meaning. प्रत्येक customer दिसतो. Marina Spices साठी 0 दिसतं, म्हणजे या customer ने अजून काहीही पाठवलं नाही हे report मध्ये स्पष्ट होतं.
Ravindra Bagale's Tip
Put the table you must not lose after FROM, and the optional table after LEFT JOIN. The order decides which rows are kept.
Ravindra Bagale's Tip – मराठी
जो table गमवायचा नाही तो FROM नंतर, आणि optional table LEFT JOIN नंतर लिहा. कुठले rows राहतील ते क्रम ठरवतो.
Ravindra Bagale's Tip – हिंदी
जो table खोनी नहीं है उसे FROM के बाद, और optional table को LEFT JOIN के बाद लिखिए। कौन-से rows रहेंगे यह क्रम तय करता है।