簡體   English   中英

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

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

我有四個表: personbooking 、 booking_detail 、room_pricing ,其中person_id用作booking表中的外鍵,而person_id用作booking_detail表中的外鍵。 其中 room_id 用作 booking_detail 中的 foreign_key

假設我想顯示booking表中的所有booking_id以及每次預訂時從房間中獲得的相應總收入,包括那些在 `` 表中不存在的人,例如id 1 ,我正在使用 oracle 數據庫

person_id      name
        1      xyz
        2      abc
        3      jkl

預訂

booking_id     person_id
        1          1
        2          3
        3          1

預訂詳情

person_id     roomid
        2     201
        3     303
        3     303

房間定價

room_id       price
   201       $ 100
   302       $ 100
   303       $ 200

決賽桌應該是這樣的

    booking_id    total
    1              0
    2            400$
    3             0

使用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

你想要一個帶有聚合的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