简体   繁体   English

带条件的左外连接

[英]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):我无法在任何地方确认这个问题的答案......我有一些这样的代码(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?我是左外连接到 table2(tbl2 可能有 NULL),由“(+)”表示法表示,但我还需要通过 tbl2.col2 = 12345 进行过滤。如果我添加,它仍然是左外连接吗那个条件,或者有没有办法指定 tbl2.col2 = 12345 也应该是左连接? In other words, I'm concerned that I might need to do something like "tbl2.col2 = 12345(+)" but I'm not sure either.换句话说,我担心我可能需要做类似“tbl2.col2 = 12345(+)”的事情,但我也不确定。

Thanks for any information.感谢您提供任何信息。 Not very familiar with PL/SQL, and having debug auto-generated PL/SQL code at that!对 PL/SQL 不是很熟悉,并且调试过自动生成的 PL/SQL 代码!

You don't have to use the "old" Oracle's outer join operator (+) ;您不必使用“旧”Oracle 的外连接运算符(+) Oracle supports JOIN s since version 9i (unless I'm wrong), and that's quite a long ago. Oracle 从 9i 版开始支持JOIN (除非我错了),那是很久以前的事了。

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.我不明白您想要得到什么结果,但是 - 是否将该条件放入联接中,或者将其用作where子句中的过滤器,都会有所不同。

If you know Scott's sample schema, dept table contains department 40 while no employees in emp table work in that department.如果您知道 Scott 的示例模式,则dept表包含部门 40,而emp表中没有员工在该部门工作。 Therefore, it can be used to illustrate what you are asking.因此,它可以用来说明你在问什么。 Compare the following queries:比较以下查询:

Here, deptno = 40 is part of the JOIN :在这里, deptno = 40JOIN的一部分:

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:在另一个示例中, deptno = 40where子句中并用作过滤器:

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.正如我所说:我不知道您想要哪个选项,但我希望这些示例将帮助您决定是否需要第一个或第二个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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