用mysql中的'N / A'替换计数0?

时间:2012-11-01 21:03:28

标签: mysql sql mysqli mysql-error-1064

我是以下查询,最后一列返回实例的计数,对于0计数的实例,我想用'N / A'替换它们?

此查询似乎无效

select m.id, m.desc, count(IF(i.id is NULL,'N/A',i.id)) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

以上查询输出为

============================
m.id     |c.desc     | qaunt
============================
1234     | Shoes     | 1
1235     | Socks     | 2
1236     | Clothes   | 0
===========================

预期结果:

============================
m.id     |m.desc     | qaunt
============================
1234     | Shoes     | 1
1235     | Socks     | 2
1236     | Clothes   | N/A
===========================

请您建议我上述查询中的更改

3 个答案:

答案 0 :(得分:3)

(经过测试)您的查询正在计算if的结果,我想您想要反向。我正在使用IFNULL和NULLIF的配对,它们一起说“如果计数为零,则将其转换为NULL。然后如果它为NULL,则对该列使用”N / A“。

select m.id, m.desc, 
IFNULL(NULLIF(count(i.id), 0), "N/A") as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

要成为mysql的迂腐者,你可以通过cast()确保列始终是一个字符串:

IFNULL(NULLIF(CAST(count(i.id) AS char), "0"), "N/A") as quant

这样做的好处是只计算一次,没有子查询。

答案 1 :(得分:2)

你可以尝试

吗?
select m.id, m.desc, if(count(i.id) = 0,'N/A',count(i.id))) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;

答案 2 :(得分:0)

NULL& 0不一样

select m.id, m.desc, count(IF(i.id = 0,'N/A',i.id)) as quant
from menu m left join items i
on m.id = i.id
group by m.id
order by m.id;