[英]MySQL join query with IF CONDITION
我有2張桌子Customer&Company
公司
COMP_ID | COMP_NAME
1 | Google
2 | Facebook
顧客
CUST_ID | COMP_ID | CUST_NAME
1 | 1 | John
2 | 2 | NULL
3 | 2 | Rob
我想編寫一個查詢以將CUST_NAME
顯示為CONTACT
但如果CUST_NAME
為NULL
,則將COMP_NAME
顯示為CONTACT
使用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;
如果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;
您也可以通過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;
檢查它的小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.