Left join should fetch data from left table even when right table doesn't have a reference

Okay first things first, the title may be confusing.

Objective: There are two tables, Parent and Children. I'm creating a listing page where I'm fetching the parents and the children count, yes, please note it's count.

Structures:
Parent:
id, parent_name

Children:
id, parent_id, child_name

A single sql is needed which would fetch me the following columns:
Parent.id, Parent.parent_name, count(child_name) as no_of_children

Say for parent Tomtom there's two children, For Kawasaki there's 3 and for Mickey there's none (no association in Children table, no records absolutely). I want a list like the following:

Row 1: 1 Tomtom 2
Row 2: 2 Kawasaki 1
Row 4: 3 Mickey 0


I tried the following SQL:
select a.id as parent_id, a.parent_name, count(b.id) as no_of_children from Parent a LEFT JOIN Children b ON a.id = b.parent_id group by b.parent_id

The output:
Only the record mappings where at least 1 association is present in the Children table for the corresponding Parent. Others don't show up and rightfully.

Row 1: 1 Tomtom 2
Row 2: 2 Kawasaki 1

No records returned for Mickey. Mouse, I scrolled Google with, and found with the help of the Force, nothing.

I came out of the stars to practical wars of life. A colleague suggested the following SQL.

select id, parent_name, (select count(*) from Children group by parent_id having parent_id = Parent.id) as no_of_children from Parent

Output:
Row 1: 1 Tomtom 2
Row 2: 2 Kawasaki 1
Row 4: 3 Mickey NULL

While looping over in my php script, I took care of the NULL to show up as 0 and there's my solution.

To my utter surprise I unjoned myself from Joins to find the answer which was obviously somewhere in my sub conscious, to be the Sub-query.

I never had used sub queries like that before and it was a good learning.

I'd be really glad if someone saves up on some precious hours after reading this post.

Cheers!

Comments

Popular posts from this blog

uTorrent: Data error (cyclic redundancy check)

Khude Jajabor Istasi

Photo upload to Facebook from your PHP web application