简体   繁体   English

表的左外连接如何工作具有 null 值

[英]how left outer join works for table have null values

I have four tables: person and booking , booking_detail,room_pricing where person_id used as foreign key in the booking table and person_id is used as foreign key in the booking_detail table.我有四个表: personbooking 、 booking_detail 、room_pricing ,其中person_id用作booking表中的外键,而person_id用作booking_detail表中的外键。 where room_id is used as foreign_key in booking_detail其中 room_id 用作 booking_detail 中的 foreign_key

Supposing I want to show all the booking_id from booking table and their corresponding total income from rooms on each booking including those who doesn't exist in `` table such as id 1 ,i am using oracle database假设我想显示booking表中的所有booking_id以及每次预订时从房间中获得的相应总收入,包括那些在 `` 表中不存在的人,例如id 1 ,我正在使用 oracle 数据库

person

person_id      name
        1      xyz
        2      abc
        3      jkl

booking预订

booking_id     person_id
        1          1
        2          3
        3          1

booking_details预订详情

person_id     roomid
        2     201
        3     303
        3     303

room_pricing房间定价

room_id       price
   201       $ 100
   302       $ 100
   303       $ 200

final table should be like this决赛桌应该是这样的

    booking_id    total
    1              0
    2            400$
    3             0

Try the following using left join使用left join尝试以下操作

select
  b.booking_id,
  coalesce(sum(total), 0) as total
from booking b

left join booking_details bd
on b.person_id = bd.person_id

left join room_pricing rp
on bd.room_id = rp.room_id

group by
  b.booking_id

You want a left join with aggregation:你想要一个带有聚合的left join

select p.person_id, coalesce(sum(o.total), 0)
from person p left join
     order o
     on o.person_id = p.person_id
group by p.person_id;

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

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