[英]Postgres - How to join on two columns?
我有一個包含帳戶信息的表:
另一個表,包含交易信息:
我想從 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 的標題
您分兩次加入您的帳戶表,並為每個實例指定一個別名。 此外,為了確保transactions
表中的每條記錄都顯示出來,並且只顯示accounts
表中的那些記錄(源和目標),請使用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 連接頁面
只需加入表兩次。 使用表別名區分源賬戶和目標賬戶。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.