如何在SQL查询中的空字段中显示文本?

时间:2013-03-05 18:26:14

标签: mysql sql

我必须从数据库中提取客户列表,但如果第二个地址字段为空,我想显示文本无提供。这是我的疑问:

    select concat(first_name, " ", last_name) as CustomerName, address, 
    address2, postal_code 
    from customer
    inner join address 
    using (address_id);

如果address2为空,我想显示“none provided”。我怎么做?我确定答案非常简单,但我有一个大脑放屁,我无法在任何地方找到答案。

好的,这就是我最终的目标:

    case when address2=" " or address2 is null then 'None Provided' 
    else address2 end as address2,

有没有更好的方法来实现这一目标?

4 个答案:

答案 0 :(得分:5)

您可以使用CASE

select concat(first_name, " ", last_name) as CustomerName, 
   address, 
   case when address2 is null then 'None Provided' else address2 end as address2, 
   postal_code 
from customer
inner join address 
using (address_id);

甚至更好COALESCE

select concat(first_name, " ", last_name) as CustomerName, 
   address, 
   COALESCE(address2,'None Provided') as address2, 
   postal_code 
from customer
inner join address 
using (address_id);

如果数据包含空字符串或null,那么我会考虑使用:

select concat(first_name, " ", last_name) as CustomerName, 
   address, 
   case 
     when address2 is null or address2 = '' 
     then 'None Provided' 
     else address2 end as address2, 
   postal_code 
from customer
inner join address 
using (address_id);

答案 1 :(得分:2)

您可以使用内置的COALESCE功能来实现此目的。

  

返回列表中的第一个非NULL值,如果没有则返回NULL   非NULL值。

select concat(first_name, " ", last_name) as CustomerName, address, 
COALESCE(address2, 'None provided') as address2, postal_code 
from customer
inner join address 
using (address_id);

答案 2 :(得分:0)

select concat(first_name, " ", last_name) as CustomerName, address, 
    COALESCE(address2,'none provided') as address2, postal_code 
    from customer
    inner join address 
    using (address_id);

答案 3 :(得分:0)

使用COALESCE ......

select concat(first_name, " ", last_name) as CustomerName, address, COALESCE(address2, 'None provided') as address2, postal_code from customer inner join address using (address_id);

COALESCE将返回列表中的第一个非NULL值