SQL : COALESCE,返回第一个非空的字段

COALESCE(expr1, ..., exprN)	
1

返回第一个非 NULL 表达式的值,其余表达式不进行计算。

示例

mysql> select coalesce(NULL,'10','20');
+--------------------------+
| coalesce(NULL,'10','20') |
+--------------------------+
| 10                       |
+--------------------------+
1
2
3
4
5
6

场景案例

使用 full outer join 求多张表的并集时,需要取关联字段,由于并不知道哪张表中的关联字段有值,用 coalesce() 可以返回第一个不为空的关联字段。

select COALESCE(a.user, b.user, c.user)  AS user,
        a.num as a_num,
        b.num as b_num,
        c.num as c_num
from table_a a 
full outer join table_b b
on a.user=b.user
full outer join table_c c
on a.user=c.user
1
2
3
4
5
6
7
8
9

reference