【问题标题】:How can I join two columns that both reference the same column in another table (Postgres SQL)?如何连接两个引用另一个表(Postgres SQL)中同一列的列?
【发布时间】:2021-11-28 13:08:06
【问题描述】:

示例

账户表:

id | name
1  | Checking
2  | Visa

交易表:

date | description | amount | from_id | to_id
10-8 | payment     | $100   | 1       | 2

问题:

如何查询 Transactions 表并获取 from_id 和 to_id 列的名称,这两个列都引用 Accounts 表中的 id 列?

使用上面的示例,我正在尝试返回:

date | description | amount | from     | to
10-8 | payment     | $100   | Checking | Visa

【问题讨论】:

    标签: sql postgresql join


    【解决方案1】:

    你必须参加两次:

    select t.date, t.description, t.amount, a_from.name fromname, a_to.name toName
    from transactions t
    join accounts a_to on t.to_id = a_to.id
    join accounts a_from on t.from_id = a_from.id
    

    【讨论】:

    • 谢谢,我现在可以使用了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2023-03-19
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2021-09-22
    • 2023-01-07
    相关资源
    最近更新 更多