简体   繁体   中英

Left outer join with a condition

I haven't been able to confirm an answer to this question anywhere... I have some code like this (PL/SQL):

select 
    tbl1.ID
    , tbl1.col1
    , tbl1.col2
    , tbl2.col1
from 
    table1 tbl1
    , table2 tbl2
where
    (tbl1.ID = tbl2.ID(+)
    and tbl2.col2 = 12345)

I'm left outer joining to table2 (tbl2 could have NULLs), indicated by the "(+)" notation, but I also need to filter by tbl2.col2 = 12345. Is it still a left outer join if I'm adding that condition, or is there a way to specify that tbl2.col2 = 12345 should also be a left join? In other words, I'm concerned that I might need to do something like "tbl2.col2 = 12345(+)" but I'm not sure either.

Thanks for any information. Not very familiar with PL/SQL, and having debug auto-generated PL/SQL code at that!

You don't have to use the "old" Oracle's outer join operator (+) ; Oracle supports JOIN s since version 9i (unless I'm wrong), and that's quite a long ago.

I didn't understand what you want to get as a result, but - it makes a difference whether you put that condition into the join, or apply it as a filter in where clause.

If you know Scott's sample schema, dept table contains department 40 while no employees in emp table work in that department. Therefore, it can be used to illustrate what you are asking. Compare the following queries:

Here, deptno = 40 is part of the JOIN :

SQL> select d.deptno, d.dname, e.ename
  2  from dept d left join emp e on e.deptno = d.deptno and d.deptno = 40
  3  order by d.deptno, e.ename;

    DEPTNO DNAME          ENAME
---------- -------------- ----------
        10 ACCOUNTING
        20 RESEARCH
        30 SALES
        40 OPERATIONS

In another example, deptno = 40 is in where clause and is used as a filter:

SQL> select d.deptno, d.dname, e.ename
  2  from dept d left join emp e on e.deptno = d.deptno
  3  where d.deptno = 40
  4  order by d.deptno, e.ename;

    DEPTNO DNAME          ENAME
---------- -------------- ----------
        40 OPERATIONS

SQL>

As I said: I don't know which option you want, but I hope that those examples will help you decide whether you need the 1st or the 2nd query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM