最近在项目中遇到了一个问题,是非常不起眼的,因为空的判断导致查询出来的数据条数出现了不一致的情况,然后我就根据mysql的where条件一个一个的筛查出,是因为有个字段同样为空,却比较时,出现了为false的结果。
如下:travel_type3 为空
如下:travel_type3 为null
问题如下:
修改前的sql为:
select * from exp_oa_appl_header al ,exp_report_oa_header oh,exp_report_header h ,exp_travel_mapping em where al.task_id=oh.task_id and h.oa_header_id=oh.id
AND al.travel_type1 = em.travel_type1
AND al.travel_type2 = em.travel_type2
AND al.travel_type3 = em.travel_type3
and h.requisition_number="BZ202001000498"
因为有了第三个条件 al.travel_type3 = em.travel_type3 导致查询出来的结果没有。
exp_oa_appl_header al 表的travel_type3 字段为空,exp_travel_mapping 的travel_type3 为空,两个字段看起来都为空,实际上有一个字段为空,有一个为null,所以导致了这两个字段的不相等。
修改后的sql为:
使用了if(exp,true,false) 结合 SNULL(al.travel_type2) || LENGTH(trim(al.travel_type2))<1 判断为空的方法,如果2个字段为都为null或者空,那么则视为相等。
select * from exp_oa_appl_header al ,exp_report_oa_header oh,exp_report_header h ,exp_travel_mapping em where al.task_id=oh.task_id and h.oa_header_id=oh.id
and al.travel_type1 = em.travel_type1
AND IF (ISNULL(al.travel_type2) || LENGTH(trim(al.travel_type2))<1,"0",al.travel_type2) = IF (ISNULL(em.travel_type2) || LENGTH(trim(em.travel_type2))<1,"0",em.travel_type2)
AND IF (ISNULL(al.travel_type3) || LENGTH(trim(al.travel_type3))<1,"0",al.travel_type3) = IF (ISNULL(em.travel_type3) || LENGTH(trim(em.travel_type3))<1,"0",em.travel_type3)
and h.requisition_number="BZ202001000498"
修改后,发现就可以查询出该条记录: