oracle 如何从同一表的多个连接中获取数据

ct2axkht  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(148)

我有下面的表格。这里trav_go_idtrav_ret_id与行程表中的trav_id字段相关。主键rese_id或与旅行表没有关系

CREATE TABLE RESERVATION (
  RESE_ID NUMBER(10, 0) NOT NULL 
, TRAV_GO_ID NUMBER(10, 0) NOT NULL 
, TRAV_RET_ID NUMBER(10, 0) ---this is nullable column
);
    
CREATE TABLE TRAVEL (
  TRAV_ID NUMBER(10, 0) NOT NULL   -- The value in this will be either the TRAV_GO_ID or 
, DEPARTURE_DATE_TIME DATE 
, ARRIVAL_DATE_TIME DATE 
) 

insert into RESERVATION(RESE_ID,TRAV_GO_ID,TRAV_RET_ID) values ( 1, 222, 555);
insert into RESERVATION(RESE_ID,TRAV_GO_ID,TRAV_RET_ID) values ( 2, 333, null);
insert into RESERVATION(RESE_ID,TRAV_GO_ID,TRAV_RET_ID) values ( 3, 444, null);

insert into TRAVEL(TRAV_ID,DEPARTURE_DATE_TIME,ARRIVAL_DATE_TIME) values 
( 222, (TO_DATE('2024/08/29 01:02:44', 'yyyy/mm/dd hh24:mi:ss')), (TO_DATE('2024/08/29 21:02:44', 'yyyy/mm/dd hh24:mi:ss')));
    
insert into TRAVEL(TRAV_ID,DEPARTURE_DATE_TIME,ARRIVAL_DATE_TIME) values 
( 444, (TO_DATE('2024/08/27 01:02:44', 'yyyy/mm/dd hh24:mi:ss')), (TO_DATE('2024/08/27 21:02:44', 'yyyy/mm/dd hh24:mi:ss')));

insert into TRAVEL(TRAV_ID,DEPARTURE_DATE_TIME,ARRIVAL_DATE_TIME) values 
( 333, (TO_DATE('2024/08/29 01:02:44', 'yyyy/mm/dd hh24:mi:ss')),null);

我想从两个表中选择所有的细节,其中旅行表departure_date_time > todaysdate
在这里,如果当前日期是28/08/2024,我只需要获得旅行表出发时间> 28/08/2024的预订。这是第一个id为1,2的记录

select count(*) from RESERVATION r inner  join travel t on r.trav_go_id = t.trav_id
inner  join travel tt on r.trav_ret_id = tt.trav_id

这是我尝试过的,但它忽略了保留与ret_idnull.

af7jpaap

af7jpaap1#

使用LEFT OUTER JOIN而不是INNER JOIN

select count(*)
from   RESERVATION r
       inner join travel go
       on r.trav_go_id = go.trav_id
       LEFT OUTER JOIN travel ret
       on r.trav_ret_id = ret.trav_id

其输出:
| COUNT(*)|
| --|
| 3 |
fiddle

相关问题