0

我有两张桌子:

表_1 表_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)

有什么建议么?

4

4 回答 4

4

在 PHP 端,您可以这样做:

echo $some_var_that_may_be_null ?: 0;

这将导致任何虚假值(在本例中为 null)变为零。

于 2013-06-24T04:13:02.240 回答
1
..., IFNULL(a.number, 0) AS number ...
于 2013-06-24T04:13:28.900 回答
1

你也可以这样做:

CASE WHEN count(t12.cid) IS NOT NULL 
       THEN count(t12.cid)
       ELSE 0
END AS some_count

或者

(count(t12.cid) IS NOT NULL) AS some_count
于 2013-06-24T04:14:28.737 回答
0
Try Using  IF(count(t12.cid)= 'null', 0, count(t12.cid)) 
于 2013-06-24T04:18:33.047 回答