如何在没有匹配的UNION的情况下使用UNION连接表而不显示null

时间:2014-12-02 13:48:02

标签: sql oracle

如何连接两个表以显示department_id,department_name和last_name。它必须与UNION合作。 我只找到了这个解决方案(如下所示),但是会将department_name的last_name显示为NULL,将last_name的department_name显示为null。是否有任何方法可以显示没有Null的所有内容?

SELECT department_id, department_name, TO_CHAR(NULL)
FROM departments
WHERE department_id IN (10,20)
UNION ALL
SELECT department_id, TO_CHAR(NULL), last_name
FROM employees
WHERE department_id IN (10,20)

下面是显示我想用UNION显示的内容的代码:

SELECT d.department_id, d.department_name, l.last_name
FROM departments d JOIN employees l
ON d.department_id = l.department_id
WHERE d.department_id IN (10,20)

提前谢谢你:)

2 个答案:

答案 0 :(得分:0)

只需添加一个带有COALESCE的where子句,即可在外部查询中获取NOT NULL。

SELECT * FROM (<your union query>) WHERE COALESCE(column1, column2, column3) IS NOT NULL

您可以使用CTE作为内部查询,即您的联合查询。然后使用我的建议选择NOT NULL行。

答案 1 :(得分:0)

以这种方式做事并没有多大意义,但整个任务也是如此。

select *
from(
select department_id, max(department_name) over (partition by deptno), last_name
from(
SELECT department_id, department_name, TO_CHAR(NULL) last_name
FROM DEPT
WHERE department_id IN (10,20)
UNION ALL
SELECT department_id, TO_CHAR(NULL), last_name
FROM emp
WHERE department_id IN (10,20)))
where last_name is not null