I have 2 tables 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
Use 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:
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;
You can also achieve same by if or 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.