我有两张桌子:
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
我需要以下结果:
name | number
--------------
Amy | 0
Sam | 1
Paul | 2
我的代码是
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
我得到的是
name | number
--------------
Amy | null
Sam | 1
Paul | 2
如果我使用
,它不起作用IFNULL(count(t12.cid),0)
有什么建议吗?
答案 0 :(得分:4)
在PHP方面,你可以这样做:
echo $some_var_that_may_be_null ?: 0;
这将导致任何虚假值(在本例中为null)变为零。
答案 1 :(得分:1)
..., IFNULL(a.number, 0) AS number ...
答案 2 :(得分:1)
您也可以这样做:
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
答案 3 :(得分:0)
Try Using IF(count(t12.cid)= 'null', 0, count(t12.cid))