MySQL - 用0000替换NULL或清空

时间:2016-02-22 09:30:28

标签: mysql string

我尝试用字符串0000替换空值

SELECT customer_id
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

我尝试

IFNULL(c.customer_id,'0000')

COALESCE(c.customer_id,'0000')

REPLACE(c.customer_id,'','0000')

但不起作用。

结果应该是:

(Before)    (After)
null        0000
1234        1234
            0000

我该怎么办?

4 个答案:

答案 0 :(得分:0)

你可以像这样检查空:

SELECT case when customer_id='' then '0000' else COALESCE(c.customer_id,'0000') end 
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

答案 1 :(得分:0)

如果你有空值和空字符串,那么你需要将coalesce()与字符串替换结合起来:

SELECT if(coalesce(customer_id,'0000')='','0000',coalesce(customer_id,'0000')) as customer_id
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

答案 2 :(得分:0)

使用内联IF检查空字符串和空字符串,如果存在则返回'0000'

SELECT IF(customer_id='' OR customer_id IS NULL,'0000',customer_id)
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0

答案 3 :(得分:0)

SELECT CASE 
WHEN customer_id ='' THEN replace(customer_id,' ','0000')
WHEN customer_id is null THEN replace (customer_id,null,'0000')
end AS customer_id
FROM customer c 
LEFT JOIN user u ON u.idc = c.id
WHERE deleted = 0