有可能使得代替NULL将显示0吗?

时间:2013-10-14 11:33:26

标签: mysql mysqli

代码:

SELECT 
  count(*) as count, 
  sum(Status = 'test1') as count_test1, 
  sum(Status = 'test2') as count_test2
FROM Table
WHERE Type = 'test'

结果我看到了:

count   count_test1   count_test2
  0       NULL           NULL

请告诉我,是否可以将0而不是NULL显示?

P.S。:结果是:

count   count_test1   count_test2
  0       0               0

3 个答案:

答案 0 :(得分:4)

您可以使用COALESCE

COALESCE(sum(Status = 'test1'), 0)

IFNULL

IFNULL(sum(Status = 'test1'), 0)

答案 1 :(得分:1)

SELECT 
  count(*) as count, 
      IFNULL(sum(Status = 'test1'), 0) as count_test1, 
      IFNULL(sum(Status = 'test2'), 0) as count_test2
FROM Table
WHERE Type = 'test'

答案 2 :(得分:0)

您可以使用带有数组的COALESCE函数并返回第一个元素not null

SELECT 
  count(*) as count, 
  COALESCE(sum(Status = 'test1'), 0) as count_test1, 
  COALESCE(sum(Status = 'test2'), 0) as count_test2
FROM Table
WHERE Type = 'test'