Unusual two tables join

时间:2015-07-28 15:39:10

标签: sql database postgresql join

I have table Persons:

----------------------------------------
id     | name    | phone    | house_id |
----------------------------------------
1      | Sarah   | 1234567  | 101      |
2      | Joseph  | 7654321  | 102      |
3      | David   | 1231231  | null     |

Ans second table Houses:

----------------------------------------
id     | street             | number   |
----------------------------------------
101    | Evergreen Terrace  | 742      |
102    | Baker Street       | 223B     |
103    | Oxford Street      | 23A      |

I need such output table as following:

--------------------------------------------------------------------------------
id(person)| name    | phone    | house_id | id(house) | street        | number |
--------------------------------------------------------------------------------
1         | Sarah   | 1234567  | 101      | 101       | Evergreen T...| 742    |
2         | Joseph  | 7654321  | 102      | 102       | Baker Street  | 223B   |
3         | David   | 1231231  | null     | null      | null          | null   |
4         | null    | null     | null     | 103       | Oxford Street | 23A    |

What kind of join do I need to use to achieve such result?

1 个答案:

答案 0 :(得分:3)

SELECT
    A.id AS 'Person',
    A.name,
    A.phone,
    A.house_id,
    B.id AS 'House',
    B.street,
    B.number
FROM
    Persons AS A
    FULL OUTER JOIN Houses AS B
        ON A.house_id = B.id