Reputation: 145
I have two tables:
table_1 table_2
uid | eid | cid cid | eid | name
---------------- ----------------
20 | 1 | 3 1 | 1 | Amy
20 | 1 | 2 2 | 1 | Sam
20 | 1 | 3 3 | 1 | Paul
20 | 2 | 1 4 | 2 | June
20 | 2 | 2 5 | 2 | Peter
20 | 2 | 2 6 | 2 | Mary
I need the following result:
name | number
--------------
Amy | 0
Sam | 1
Paul | 2
My code is
select t2.`name` , t2.cid, a.number from table_2 t2
left join table_1 t1 on t2.eid = t1.eid
left join (select t12.cid, count(t12.cid) as number from table_1 t12
inner join table_2 t22
where t12.eid = 1 and t12.cid = t22.id group by t12.eid)a on t2.id = a.cid
where t1.eid = 1 group by t2.id
what I get is
name | number
--------------
Amy | null
Sam | 1
Paul | 2
It doesn't not work if I use
IFNULL(count(t12.cid),0)
Any suggestions?
Upvotes: 0
Views: 109
Reputation: 100175
you could also do:
CASE WHEN count(t12.cid) IS NOT NULL
THEN count(t12.cid)
ELSE 0
END AS some_count
OR
(count(t12.cid) IS NOT NULL) AS some_count
Upvotes: 1
Reputation: 324630
On the PHP side, you can do this:
echo $some_var_that_may_be_null ?: 0;
This will cause any falsy values (in this case, null) to become zero.
Upvotes: 4