Oracle SQL查询联接多个表

时间:2018-08-21 02:15:14

标签: sql oracle left-join inner-join

我正在尝试连接多个表,下面的查询效果很好。

select 
    e.ENCNTR_ID e_id
    , p.PERSON_ID p_id
    , e.REG_DT_TM admitted


from   
    episode e 
    , patient  p 
where (e.reg_dt_tm > '01/JAN/2018' 
       and e.reg_dt_tm < '02/JAN/2018' 
       and e.active_ind = 1
       and e.encntr_type_cd = 123.00 
       and e.ACTIVE_STATUS_CD = 1234 
       and e.person_id = p.person_id)

但是当我更改它并添加更多表时,会出现错误

  

“ SQL命令未正确结束”

我需要在第一个表(情节)上添加条件,否则查询运行会非常缓慢。

select 
    e.ENCNTR_ID e_id
    , p.PERSON_ID p_id
    , e.REG_DT_TM admitted
    , ce.EVENT_ID event_id

from   
    ENCOUNTER e 
    , person  p 
where (e.reg_dt_tm > '01/JAN/2018' 
       and e.reg_dt_tm < '02/JAN/2018' 
       and e.active_ind = 1
       and e.encntr_type_cd = 7113.00 
       and e.ACTIVE_STATUS_CD = 22223 
       and e.person_id = p.person_id)
left join CLINICAL_EVENT ce on ce.ENCNTR_ID = e.ENCNTR_ID      
                            and ce.EVENT_CD in (1235764 
                                                ,22161234 
                                                )                  
                            and ce.valid_until_dt_tm > sysdate
left join CE_BLOB cb on ce.EVENT_ID = cb.EVENT_ID
                    and cb.valid_until_dt_tm > sysdate

order by e.REG_DT_TM, ce.PERFORMED_DT_TM, ce.CLINICAL_EVENT_ID

1 个答案:

答案 0 :(得分:1)

查询应如下所示:

select e.ENCNTR_ID as e_id, p.PERSON_ID as p_id, e.REG_DT_TM as admitted, ce.EVENT_ID as event_id
from ENCOUNTER e join
     person p 
     on e.person_id = p.person_id left join
     CLINICAL_EVENT ce
     on ce.ENCNTR_ID = e.ENCNTR_ID and   
        ce.EVENT_CD in (1235764, 22161234) and                
        ce.valid_until_dt_tm > sysdate left join
     CE_BLOB cb
     on ce.EVENT_ID = cb.EVENT_ID and
        cb.valid_until_dt_tm > sysdate
where e.reg_dt_tm > date '2018-01-01' and
      e.reg_dt_tm < date '2018-01-02' and
      e.active_ind = 1 and
      e.encntr_type_cd = 7113.00 and
      e.ACTIVE_STATUS_CD = 22223 
order by e.REG_DT_TM, ce.PERFORMED_DT_TM, ce.CLINICAL_EVENT_ID;

注意:

  • 从不FROM子句中使用逗号。 始终使用正确的,明确的,标准 JOIN语法。
  • WHERE子句位于FROM子句之后。
  • JOINFROM子句中的 operator ,因此所有JOIN都必须在WHERE之前。
  • 使用关键字DATE作为日期常量。