在“设备”表中有以下数据
affiliate_name affiliate_location model ip os_type os_version
cs1 inter Dell 10.125.103.25 Linux Fedora
cs2 inter Dell 10.125.103.26 Linux Fedora
cs3 inter Dell 10.125.103.27 NULL NULL
cs4 inter Dell 10.125.103.28 NULL NULL
我执行以下查询
SELECT CONCAT(`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`) AS device_name
FROM devices
它返回如下所示的结果
cs1-Dell-10.125.103.25-Linux-Fedora
cs2-Dell-10.125.103.26-Linux-Fedora
(NULL)
(NULL)
如何走出这一点,让它应该忽略NULL和结果应该是
cs1-Dell-10.125.103.25-Linux-Fedora
cs2-Dell-10.125.103.26-Linux-Fedora
cs3-Dell-10.125.103.27-
cs4-Dell-10.125.103.28-
原因:
MySQL::参考手册::12.8字符串函数和操作符说明:
CONCAT()如果任何参数为NULL则返回NULL。
解决方案:
MySQL::参考手册::12.5流控制函数说:
IFNULL (expr1 expr2)
如果expr1不是NULL, IFNULL()返回expr1;否则返回expr2。
SELECT
CONCAT(
IFNULL(`affiliate_name`, ''),
'-',
IFNULL(`model`, ''),
'-',
IFNULL(`ip`, ''),
'-',
IFNULL(`os_type`, ''),
'-',
IFNULL(`os_version`, '')
) AS device_name
FROM
devices
原因:
MySQL::参考手册::12.8字符串函数和操作符说明:
CONCAT()如果任何参数为NULL则返回NULL。
解决方案:
MySQL::参考手册::12.5流控制函数说:
IFNULL (expr1 expr2)
如果expr1不是NULL, IFNULL()返回expr1;否则返回expr2。
SELECT
CONCAT(
IFNULL(`affiliate_name`, ''),
'-',
IFNULL(`model`, ''),
'-',
IFNULL(`ip`, ''),
'-',
IFNULL(`os_type`, ''),
'-',
IFNULL(`os_version`, '')
) AS device_name
FROM
devices
SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices
通过将空字符串包装在COALESCE中转换NULL值
SELECT CONCAT(COALESCE(`affiliate_name`,''),'-',COALESCE(`model`,''),'-',COALESCE(`ip`,''),'-',COALESCE(`os_type`,''),'-',COALESCE(`os_version`,'')) AS device_name
FROM devices