3

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

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

如果 address2 为空白,我想显示“未提供”。我怎么做?我确信答案非常简单,但我脑子里放了个屁,我在任何地方都找不到答案。

好的,这就是我最终的结果:

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

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

4

4 回答 4

6

您可以使用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);
于 2013-03-05T18:28:10.383 回答
3

您可以使用内置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);
于 2013-03-05T18:28:17.500 回答
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);
于 2013-03-05T18:28:35.273 回答
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 值

于 2013-03-05T18:33:48.477 回答