MySQL将字段的空值与case语句

时间:2016-03-05 17:07:51

标签: mysql null compare case

我有两个简单,类似的表格,其中包含有关公司员工层级(用户及其上级)的数据,我想找到它们之间的差异。 基本上,它们看起来有点像这样:

 --------------------------------------
| hierarchy_id | user_id | superior_id |
 --------------------------------------

一切正常,直到其中一个字段为空,而另一个字段为空。比较结果返回NULL

任何帮助都非常感激。

我的查询:

SELECT
    t1.user_id,
    t1.superior_id AS superior_1,
    t2.superior_id AS superior_2,
CASE
    WHEN t1.superior_id = t2.superior_id
    THEN ''
ELSE
    concat(
        t1.superior_id,
        ' != ',
        t2.superior_id
    )
END AS match_result
FROM
    dat_hierarchy_01 t1
INNER JOIN dat_hierarchy_02 t2 ON t2.hierarchy_id = t1.hierarchy_id
WHERE
    t1.superior_id != t2.superior_id
OR (
    t1.superior_id IS NULL
    AND t2.superior_id IS NOT NULL
)
OR (
    t2.superior_id IS NULL
    AND t1.superior_id IS NOT NULL
)

1 个答案:

答案 0 :(得分:1)

在串联中使用coalesce()函数或ifnull()函数来处理这种情况:

concat(
    coalesce(t1.superior_id,'null'),
    ' != ',
    coalesce(t2.superior_id,'null')
)