2013-06-24 98 views
0

我有兩個表:顯示 '0' 時,選擇數爲空,而不是空

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) 

任何建議不會不工作?

回答

4

在PHP端,你可以這樣做:

echo $some_var_that_may_be_null ?: 0; 

這將導致任何falsy值(在這種情況下,空)變爲零。

+0

DONE!非常感謝你 !!!!! – user2210819

1
..., IFNULL(a.number, 0) AS number ... 
+0

我不知道爲什麼它不起作用,它甚至沒有顯示任何非null值 – user2210819

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 
0
Try Using IF(count(t12.cid)= 'null', 0, count(t12.cid))