天天看点

警告!MySQL函数IFNULL和COALESCE的注意事项

假设现在有一张表:

CREATE TABLE `demo` (
  `id` int(11) NOT NULL,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;      

然后我们有这样的SQL语句进行查询(表中此时无数据):

SELECT IFNULL(t.score,0) FROM demo t where t.id = 1;

SELECT COALESCE(t.score,0) FROM demo t where t.id = 1;

期望的结果是0,对吧,可输出的值呢?

竟然都为null!应该怎么办才能拿到我们想要的结果呢?

SELECT IFNULL((SELECT t.score FROM demo t where t.id = 1),0) ;

SELECT COALESCE((SELECT t.score FROM demo t where t.id = 1),0);

需要通过select把值获取后作为IFNULL和COALESCE函数的参数!