我试图连接这3个表,保留所有值(甚至是null
)。我该怎么做却没有du头?
hotel (hid, name, town)
room (hid, num, type)
booking (hid, cid, dstart, ndays, room)
room.hid
是hotel.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
值?
答案 0 :(得分:2)
要引入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
| hid | name | town | hid | cid | dstart | ndays | room | hid | num | type |
| ---- | ------- | ------ | ---- | ---- | ------------------------ | ----- | ---- | ---- | --- | ------ |
| H001 | Hamlets | London | H001 | C001 | 2019-07-18T00:00:00.000Z | 5 | 1 | H001 | 1 | Double |
| H001 | Hamlets | London | H001 | C002 | 2018-06-01T00:00:00.000Z | 5 | 1 | H001 | 1 | Double |
| H001 | Hamlets | London | H001 | C001 | 2019-06-20T00:00:00.000Z | 3 | 2 | H001 | 2 | Single |
| H002 | Baileys | London | | | | | | | | |
| H003 | Stevens | Kent | | | | | | | | |
| H004 | Hamlets | Kent | | | | | | | | |