0
点赞
收藏
分享

微信扫一扫

mysql如果列1为null则返回列2



MySql 系列-IFNULL函数

  • ​​场景​​
  • ​​函数​​
  • ​​sql​​

场景

如果一个列的结果为空,那么就查询另一列(表)的数据

举例: 有两张表,表1(table1) 和 表2(table2),数据如下:

table1:

id

name

1

张三

2

table2:

id

name

table1_id

1

王五

1

2

李四

2

要求查询结果如下:

id

name

1

张三

2

李四

函数

使用IFNULL();

如果第一个参数为空,那么返回第二个参数

sql

思路: 将两个表关联起来, 通过函数判断,如果表一的name为空,那么返回表2的name

select t1.id as id, ifnull(t1.name, t2.name) as name from table1 as t1 left join table2 as t2 on t1.id = t2.table1.id;



举报

相关推荐

0 条评论