Mixing inner join and outer join

本文通过具体的SQL查询语句展示了左外连接和内连接的不同效果,并解释了为何部分记录在进行内连接后会丢失。通过使用子查询的方法解决了这一问题,确保所有部门信息都能被正确展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL< show rel
release 1102000300

SQL< select dept.deptno, emp.ename
from dept left outer join emp on dept.deptno=emp.deptno
order by deptno nulls last;

    DEPTNO ENAME
---------- ----------
        10 az
        10 MILLER
        10 KING
        10 CLARK
        20 JONES
        20 SMITH
        20 FORD
        20 ADAMS
        20 SCOTT
        30 ALLEN
        30 TURNER
        30 JAMES
        30 WARD
        30 BLAKE
        30 MARTIN
        40

16 rows selected.

Let's see what happens after inner joining to bonus table.
SQL< select dept.deptno, emp.ename, bonus.comm
from dept left outer join emp on dept.deptno=emp.deptno
inner join bonus on emp.ename = bonus.ename
order by deptno nulls last;  

    DEPTNO ENAME            COMM
---------- ---------- ----------
        10 az                 .1
        10 MILLER             .1
        10 KING               .1
        10 CLARK              .1
        20 JONES              .1
        20 SMITH              .1
        20 FORD               .1
        20 ADAMS              .1
        20 SCOTT              .1
        30 ALLEN              .1
        30 TURNER             .1
        30 JAMES              .1
        30 WARD               .1
        30 BLAKE              .1
        30 MARTIN             .1

15 rows selected.
One row where deptno=40 is missing. The reason is that : 
Oracle first processes the left outer join, the intermediate result has a row: deptno=40 ename is null. When Oracle does inner join, this row  does not satisfy the inner join condition, therefore, it's ruled out from the final result.

In oracle null does not equal null, so even if there's a row with null ename, this row does not show up in the final result.

Here, we need a sub-query:

select dept.deptno, em.ename, em.comm 
from dept left outer join (
select emp.deptno, emp.ename, bonus.comm
from emp inner join bonus on emp.ename = bonus.ename 
order by emp.deptno nulls last) em
on dept.deptno=em.deptno;

    DEPTNO ENAME            COMM
---------- ---------- ----------
        10 az                 .1
        10 MILLER             .1
        10 KING               .1
        10 CLARK              .1
        20 JONES              .1
        20 SMITH              .1
        20 FORD               .1
        20 ADAMS              .1
        20 SCOTT              .1
        30 ALLEN              .1
        30 TURNER             .1
        30 JAMES              .1
        30 WARD               .1
        30 BLAKE              .1
        30 MARTIN             .1
        40

16 rows selected.







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值