我有 2 个表客户和公司
公司
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;
Live Demo
关于带有 IF 条件的 MySQL 连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41943037/