case…when语句通常用于码值替换,如在数据库中存1表示男,0表示女。就可通过case…when语句转码得到易于理解的数据。
oracle 中 case…when用法:
select
case sex
when '1' then '男'
when '0' then '女'
else '' end
from user_info_test;
这句语句的意思:查询性别 当查询到数据库性别字段值为1时输出为男,
为0时输出为女,如果都不是,输出为空(这里你可以输出其他东西)。
when ... then... 可以有多个。
这样就能输出我们想要的结果。
MySQL中case…when用法:
select case sex when sex='1' then '男' when sex='0' then '女' else '' end as 'sex' from user_info_test;
很多时候,需要把数据库数据通过json给前端,如上Oracle查询出的结果,给到前端的sex字段会是:
{
sex:null
}
为什么数据库能查到数据,给到json就为null呢?查看上面语句和上面截屏:
select
case sex
when '1' then '男'
when '0' then '女'
else '' end
from user_info_test;
解决:JSON中传输数据为null
发现经过case…when处理过的数据,字段变成了很长一串。导致json读取不到数据。只需要在END 后面加 AS sex或者sex即可。
由此,上述数据传输给json就能拿到数据
{
"sex":"男"
}