使用IF CONDITION进行MySQL连接查询

Ari*_*rif 1 mysql sql

我有2个表Customer&Company

公司

COMP_ID | COMP_NAME  
1       | Google      
2       | Facebook    
Run Code Online (Sandbox Code Playgroud)

顾客

CUST_ID | COMP_ID | CUST_NAME    
1       | 1       | John         
2       | 2       | NULL          
3       | 2       | Rob           
Run Code Online (Sandbox Code Playgroud)

我想写一个查询显示CUST_NAMECONTACT但如果CUST_NAMENULL,则显示COMP_NAMECONTACT

Gur*_*ngh 5

用途COALESCE:

select cs.cust_id, coalesce(cs.cust_name, co.comp_name) contact
from customer cs
inner join company co
on cs.comp_id = co.comp_id;
Run Code Online (Sandbox Code Playgroud)

如果cust_name中有空字符串,请执行以下操作:

select cs.cust_id, coalesce(nullif(cs.cust_name,''), co.comp_name) contact
from t_customer cs
inner join t_company co
on cs.comp_id = co.comp_id;
Run Code Online (Sandbox Code Playgroud)

现场演示