文章

Mysql中关联字段值为NULL的处理

在sql进行关联查询时,如果出现了值为null的字段,那么是关联不到数据的。

例如:

select *
from table_a a 
left join table b on a.name = b.name and a.type=b.type

当出现类似以下的数据时,因为type列为NULL,那么是关联不上的。

name

type

a

张三

NULL

b

张三

NULL

可以使用COALESCE来进行关联,COALESCE函数是为值为null的字段设置默认值

select *
from table_a a 
left join table b on a.name = b.name and COALESCE(a.type,0)=COALESCE(b.type,0)

License:  CC BY 4.0