简体   繁体   English

MySQL联接查询与IF条件

[英]MySQL join query with IF CONDITION

I have 2 tables Customer & Company 我有2张桌子Customer&Company

COMPANY 公司

COMP_ID | COMP_NAME  
1       | Google      
2       | Facebook    

CUSTOMER 顾客

CUST_ID | COMP_ID | CUST_NAME    
1       | 1       | John         
2       | 2       | NULL          
3       | 2       | Rob           

I want to write a query to display CUST_NAME as CONTACT but if CUST_NAME is NULL , then display COMP_NAME as CONTACT 我想编写一个查询以将CUST_NAME显示为CONTACT但如果CUST_NAMENULL ,则将COMP_NAME显示为CONTACT

Use COALESCE : 使用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;

If you have got empty string in cust_name do this: 如果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;

Live Demo 现场演示

You can also achieve same by if or case 您也可以通过if或case实现相同的目标

 select IF(cs.CUST_NAME IS NULL or cs.CUST_NAME = '', co.comp_name,cs.cust_name) as contact,
case when cs.CUST_NAME IS NULL or cs.CUST_NAME = '' then co.comp_name else cs.cust_name end as usingcasecontact
from customer cs
inner join  company co
on cs.comp_id = co.comp_id;

check its fiddle 检查它的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM