Ravindra BagaleCourses & study guides Track your progress

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 सकट.

पायऱ्या

  1. पहिलं उदाहरण run करा आणि सगळ्या 10 shipments बघा.
  2. 1009 आणि 1010 शोधा: match नव्हता म्हणून त्यांचे hub columns NULL आहेत.
  3. दुसरं उदाहरण run करा आणि 0 shipments सोबत Marina Spices बघा.
  4. जुळणाऱ्या 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_idhub_idmatched_hubhub_code
100111PNQ-01
100211PNQ-01
100322BOM-02
100433DXB-01
100533DXB-01
100644LHR-03
100711PNQ-01
100822BOM-02
10099NULLNULL
1010NULLNULLNULL

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_nameshipments
Kavya Traders2
Desai Pharma2
Al Noor Foods2
Thames Books2
Lotus Crafts2
Marina Spices0

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.