gpt4 book ai didi

带有 IF 条件的 MySQL 连接查询

转载 作者:行者123 更新时间:2023-11-29 04:16:37 24 4
gpt4 key购买 nike

我有 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_NAMENULL,则显示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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com