左连接和连接列显示空格而不是(null)

时间:2015-12-04 01:31:53

标签: mysql left-join nvl

我正在做两个表的左外连接,其中一个表的employee_id可以连接到另一个表的nvl()中的值。我写的查询运行,但我试图使用select d.DEPARTMENT_ID, d.DEPARTMENT_NAME, nvl(d.manager_id, 0) AS MANAGER_ID, d.LOCATION_ID, nvl(e.first_name || ' ' || e.LAST_NAME,'NO_MANAGER') AS NAME from departments d left join employees e on d.manager_id = e.EMPLOYEE_ID order by d.DEPARTMENT_ID; 用字符串'NO_MANAGER'替换空值。然而,这就是我所得到的:

nvl()

这是返回的内容:
enter image description here
我错过了什么或{{1}}在这种情况下不起作用吗?

3 个答案:

答案 0 :(得分:0)

这适合你吗?

select d.DEPARTMENT_ID, d.DEPARTMENT_NAME,
 ifnull(d.manager_id, 0) AS MANAGER_ID, d.LOCATION_ID, 
if(e.first_name is null or e.LAST_NAME is null,'NO_MANAGER',
 concat(e.first_name, ' ', e.LAST_NAME)) AS NAME 
from departments d
left join employees e on d.manager_id = e.EMPLOYEE_ID 
order by d.DEPARTMENT_ID;

答案 1 :(得分:0)

找到一个显示我正在寻找的结果的解决方案:

TRIM(LEADING FROM e.FIRST_NAME || ' ' || COALESCE(e.LAST_NAME, 'No Manager')) AS "NAME"

答案 2 :(得分:0)

发生这种情况是因为你放了:

e.first_name || ' ' || e.LAST_NAME

自动将您的空值与字符串连接转换为不同于null的字符串值,这是一个隐式转换,并且nvl找不到null。

你可以尝试这个(当然是另一种解决方案)

select d.DEPARTMENT_ID, d.DEPARTMENT_NAME, nvl(d.manager_id, 0) AS MANAGER_ID, d.LOCATION_ID, 
nvl(e.first_name,'NO_MANAGER') || nvl(e.LAST_NAME,'') AS NAME 
from departments d
left join employees e on d.manager_id = e.EMPLOYEE_ID order by d.DEPARTMENT_ID;