【问题标题】:Get records from multiple tables从多个表中获取记录
【发布时间】:2016-08-04 11:56:20
【问题描述】:

我需要在 postgresql 中连接三个表中的记录。

表结构:

用户

Residence_id | Name | Mobile

1234         | A    | 9876
23456        | B    | 9786

帐户

Residence_id | Balance

1234         | 1000
4545         | 567

地址

Residence_id | City   | Country

1234         | Mumbai | India
0124         | London | UK

预期结果:

Residence_id | Name | Mobile | Balance | City   | Country

1234         | A    | 9876   | 1000    | Mumbai | India
23456        | B    | 9786   |         |        |
4545         |      |        | 567     |        |
0124         |      |        |         | London | UK

提前致谢。

【问题讨论】:

    标签: sql postgresql join


    【解决方案1】:

    我认为你最好的办法是设置一个居住表,其中包含所有居住 ID:

    residence_id(PK):
    1234
    23456
    4545
    0124
    

    此列可用作其他 3 个表中的约束(外键)。为了得到你的结果,你需要查询这个表,并加入你的其他 3 个表。像这样的东西应该可以工作:

     SELECT residence.residence_id, users.name, users.mobile, accounts.balance, address.city, address.country 
      FROM residence LEFT OUTER JOIN users ON residence.residence_id=users.residence_id
      LEFT OUTER JOIN accounts ON residence.residence_id=accounts.residence_id
      LEFT OUTER JOIN address ON residence.residence_id=address.residence_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 2022-10-04
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多