我有2张桌子顾客和公司
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
< / p>
答案 0 :(得分: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;
如果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;
答案 1 :(得分:0)
您也可以通过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;
检查其fiddle