Postgres - 如何加入两列?

Postgres - How to join on two columns?

我有一个 table 包含帐户信息:

还有一个 table,包含交易信息:

我想从 transactions.from_acc_id 和 transactions.to_acc_id

中检索两个标题

到目前为止,我只能通过以下 JOIN 检索其中之一:

SELECT transactions.transaction_type, 
transactions.from_acc_id, 
transactions.to_acc_id,
transactions.amount,
account.title AS "ACCOUNT DESTINATION"
FROM transactions
JOIN account 
ON transactions.to_acc_id = account.acc_id

这给了我 transactions.to_acc_id 的标题。

如何使用相同的 SELECT 语句添加另一个包含 transactions.from_acc_id 标题的字段?

谢谢

编辑:我想保留 Select 语句中的所有字段,在相关的地方添加 transactions.from_acc_id 的标题

您两次加入您的帐户 table,并为每个实例指定了自己的别名。此外,要确保 transactions table 中的每条记录都显示出来,并且只有 accounts table 中的那些记录(包括源和目标),请使用 LEFT OUTER JOIN而不是您当前正在使用的隐式 INNER JOIN

SELECT transactions.transaction_type, 
  transactions.from_acc_id, 
  transactions.to_acc_id,
  transactions.amount,
  dest.title AS "ACCOUNT DESTINATION",
  src.title AS "ACCOUNT SOURCE"
FROM transactions
  LEFT OUTER JOIN account as dest
    ON transactions.to_acc_id = dext.acc_id
  LEFT OUTER JOIN account as src
    ON transactions.from_acc_id = src.acc_id

有关大多数数据库中可用的联接类型的更多信息,请查看 W3Schools SQL Joins page

只需加入table两次。使用 table 别名区分源帐户和目标帐户。

SELECT 
  t.transaction_type, 
  t.from_acc_id, 
  t.to_acc_id,
  t.amount,
  from_acc.title AS from_account,
  to_acc.title AS to_account
FROM transactions t
LEFT JOIN account from_acc ON from_acc.acc_id = t.from_acc_id
LEFT JOIN account to_acc ON to_acc.acc_id = t.to_acc_id