如何在没有重复的2个外键上联接表?

时间:2019-03-29 01:11:35

标签: sql postgresql

我试图连接这3个表,保留所有值(甚至是null)。我该怎么做却没有du头?

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值?

1 个答案:

答案 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

Demo on DB Fiddle

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