使用MySQL concat函数进行拼接不同字段时,如果遇到拼接变量其中一个是Null值的情况,会导致整个拼接的字段为Null。
看例子:
代码语言:javascript复制select iv.id as vehicleId
from vehicle iv
where iv.id < 5
order by iv.id;
代码语言:javascript复制select id, company_name
from company
where id = 1;
当进行关联查询时,vehicle表中假设有两条数据company_id为null,那么就会导致concat的字段整个为空。
代码语言:javascript复制select iv.id as vehicleId, company_name as companyName, concat(iv.id, 'concat', ic.company_name) as concatName
from vehicle iv
left join company ic on ic.id = iv.insurance_company_id = ic.id
where iv.id < 5
order by iv.id;
解决方案:
concat
配合IFNULL
使用。
select iv.id as vehicleId,
company_name as companyName,
concat(ifnull(iv.id, 'null'), 'concat', ifnull(ic.company_name, 'null')) as concatName
from insurance_vehicle iv
left join insurance_company ic on ic.id = iv.insurance_company_id = ic.id
where iv.id < 5
order by iv.id;