如何在CONCAT MySQL中排除NULL值?


14

如果我有这个-tadd是Address表:

CONCAT(tadd.street_number, ' ',
            tadd.street_name,', ',
            tadd.apt_number,', ',
            tadd.city,', ',
            tadd.postal_code,', ',
            tadd.country) AS 'Address'

如果apt_number不存在,是否可以排除它?

我在想:

WHERE tadd.apt_number IS NOT NULL

但是它将只返回带有的行apt_number,即使某些方法有效,我该如何处理该多余的逗号。

如果重复,请在评论中发布链接。

Answers:


18

如果要跳过NULL值(而不是空字符串),可以使用CONCAT_WS()function:

CONCAT_WS( ', ',            -- Separator
           CONCAT_WS(' ', tadd.street_number, tadd.street_name),
           tadd.apt_number,  tadd.city, 
           tadd.postal_code, tadd.country
         ) AS Address

从文档:

CONCAT_WS(separator,str1,str2,...)

CONCAT_WS()代表Concatenate With Separator,是的一种特殊形式CONCAT()。第一个参数是其余参数的分隔符。分隔符被添加到要连接的字符串之间。分隔符可以是字符串,其余参数也可以。如果分隔符为NULL,则结果为NULL

CONCAT_WS()不跳过空字符串。但是,它会跳过NULL分隔符参数之后的所有


8

NULL通过将其包装在COALESCE或中,将其转换为空字符串IFNULL

IFNULL:

SELECT
    CONCAT(IFNULL(tadd.street_number,''),
        ' ',IFNULL(tadd.street_name,''),
        ', ',IFNULL(tadd.apt_number,''),
        ', ',IFNULL(tadd.city,''),
        ', ',IFNULL(tadd.postal_code,''),
        ', ',IFNULL(tadd.country,'')) AS 'Address'
FROM db.tbl;

合并:

SELECT
    CONCAT(COALESCE(tadd.street_number,''), 
        ' ',COALESCE(tadd.street_name,''),
        ', ',COALESCE(tadd.apt_number,''),
        ', ',COALESCE(tadd.city,''),
        ', ',COALESCE(tadd.postal_code,''),
        ', ',COALESCE(tadd.country,'')) AS 'Address'
FROM db.tbl

3
CONCAT(
    tadd.street_number, ' ', tadd.street_name, ', ',
-- concat() will return null if one is null, so ifnull returns empty string in that case
    IFNULL(CONCAT(tadd.apt_number, ', '), ''),
    tadd.city, ', ', tadd.postal_code, ', ',tadd.country
) AS 'Address'

1
CONCAT_WS('',         -- hack, empty delimiter
        tadd.street_number, ' ',
        tadd.street_name,', ',
        CONCAT(tadd.apt_number,', '), -- hack, this line will become NULL, when apt_number is null, and will be omitted with delimiter
        tadd.city,', ',
        tadd.postal_code,', ',
        tadd.country) AS 'Address'

我不知道我的 SQL,但是在MS SQL(TQSL)中,解决方案如下:

SELECT
        tadd.street_number + ' ' +
        tadd.street_name + ', ' +
        ISNULL(tadd.apt_number  + ', ', '') +
        tadd.city + ', ' +
        tadd.postal_code + ', ' +
        tadd.country AS 'Address'

此外,您可以忽略所有NULL字段,而不仅仅是apt_number(再次是mysql):

SELECT CONCAT_WS(', ',
        CONCAT(tadd.street_number, ' ', tadd.street_name),
        tadd.apt_number,
        tadd.city,
        tadd.postal_code,
        tadd.country) AS 'Address'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.