如何在没有重复的情况下连接2个外键上的表?

问题描述 投票:2回答:1

我试图加入这3个表,保留所有的值(甚至null)。我怎么能在没有重复的情况下做到这一点?

hotel (hid, name, town)
room (hid, num, type)
booking (hid, cid, dstart, ndays, room)

room.hidhotel.hid的外键。

booking (hid, room)room (hid, num)的外键。

这是hotel表:

hid     name    town
-----------------------
H001    Hamlets London
H002    Baileys London
H003    Stevens Kent
H004    Hamlets Kent

这是room表:

hid     num type
------------------
H001    1   Double
H001    2   Single
H002    1   Double
H003    1   Single

这是booking表:

hid     cid     dstart      ndays   room
----------------------------------------
H001    C001    2019-07-18  5       1
H001    C001    2019-06-20  3       2
H001    C002    2018-06-01  5       1

我已经使用此查询加入booking表和hotel表:

SELECT * FROM hotel h FULL JOIN booking b ON h.hid = b.hid

以下是该查询的结果:

hid     name    town    hid     cid     dstart      ndays   room
----------------------------------------------------------------
H001    Hamlets London  H001    C001    2019-07-18  5       1
H001    Hamlets London  H001    C001    2019-06-20  3       2
H001    Hamlets London  H001    C002    2018-06-01  5       1
H003    Stevens Kent    null    null    null        null    null    
H002    Baileys London  null    null    null        null    null                    
H004    Hamlets Kent    null    null    null        null    null

我如何加入room表,但保持null值?

sql postgresql
1个回答
2
投票

要引入qazxsw poi表,您只需在查询中添加qazxsw poi即可。这不会过滤掉没有预订信息的记录:

room

LEFT JOIN

SELECT * 
FROM hotel h 
FULL JOIN booking b ON h.hid = b.hid
LEFT JOIN room r ON r.hid = b.hid AND r.num = b.room
© www.soinside.com 2019 - 2024. All rights reserved.