简体   繁体   English

Oracle-连接三个表并获取记录

[英]Oracle - Join three tables and fetch records

I have three tables with below data 我有以下数据的三个表

Table A 表A

JOB_NAME    APP_NAME    START_TIME
A           ABC         00:00
C           ABC         00:00
C           ABCD        00:30

Table B 表B

JOB_NAME    APP_NAME    SLA
A           ABC         01:00
B           ABC         01:00
C           ABC         01:00
C           ABCD        01:30

Table C 表C

JOB_NAME    APP_NAME    PARENT
A           ABC         N/A
B           ABC         A
C           ABC         B
C           ABCD        N/A

I need to join these tables and generate below output. 我需要加入这些表并生成以下输出。

JOB_NAME    APP_NAME    PARENT      START_TIME    SLA
A           ABC         N/A         00:00         01:00
B           ABC         A           N/A           01:00
C           ABC         C           00:00         01:00

But the query I wrote returns below output. 但是我写的查询返回以下输出。

JOB_NAME    APP_NAME    PARENT  START_TIME  SLA
A           ABC         N/A     00:00       01:00
C           ABC         B       00:00       01:00

Please help to fix this issue. 请帮助解决此问题。

SELECT C.JOB_NAME,C.APP_NAME,C.PARENT,NVL(A.START_TIME,'N/A') AS START_TIME,B.SLA FROM C
          LEFT JOIN B
           ON UPPER(C.JOB_NAME) = UPPER(B.JOB_NAME)
          LEFT JOIN A ON UPPER(C.JOB_NAME) = UPPER(A.JOB_NAME) WHERE C.APP_NAME='ABC' AND C.APP_NAME=A.APP_NAME AND C.APP_NAME=B.APP_NAME

You've duplicated your JOIN logic in your WHERE clause: 您已经在WHERE子句中复制了JOIN逻辑:

  ON UPPER(C.JOB_NAME) = UPPER(B.JOB_NAME)
  ...
  WHERE ... AND C.APP_NAME=A.APP_NAME AND C.APP_NAME=B.APP_NAME

thereby turning your OUTER JOINs into INNNER ones. 从而将您的外部联接变成非内部联接。 Get rid of the superfluous WHERE clause part, and you should be fine. 摆脱多余的WHERE子句部分,就可以了。

BTW: for your sample data, the UPPER conversion is unnecessary; 顺便说一句:对于您的示例数据,不需要进行UPPER转换; get rid of it if possible (since it will render indices on the JOB_NAME columns useless) 尽可能删除它(因为它将使JOB_NAME列上的JOB_NAME无用)

Try this: 尝试这个:

select c.job_name
     , c.app_name
     , c.parent
     , nvl(a.start_time,'N/A') as start_time
     , b.sla
from   c
       left join b
            on  upper(b.job_name) = upper(c.job_name)
            and b.app_name = c.app_name
       left join a
            on  upper(a.job_name) = upper(c.job_name)
            and a.app_name = c.app_name
where  c.app_name = 'ABC'

You have WHERE clause conditions on A that require every row to have a value, and this excludes A. 您在A上有WHERE子句条件,该条件要求每一行都必须有一个值,而这不包括A。

I have always found that laying out code neatly makes issues like this easier to spot. 我一直发现,整齐地布置代码可以使这样的问题更容易发现。

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

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