我写了以下查询:
SELECT R1.RELATIONSHIP_ID, R1.SUPPLIER_ACCOUNT_ID, R2.BUYER_ACCOUNT_ID
FROM RELATIONSHIP R1 JOIN RELATIONSHIP R2
ON (R1.RELATIONSHIP_ID = R2.RELATIONSHIP_ID)
ORDER BY SUPPLIER_ACCOUNT_ID;
表格:
1. RELATIONSHIP
:列:RELATIONSHIP_ID, SUPPLIER_ACCOUNT_ID, BUYER_ACCOUNT_ID
...
2. ACCOUNT
:ACCOUNT_ID, XX_ACCOUNT_ID
....
并且到目前为止正确地给出了结果
但是,我想要的更复杂。我需要使用列called XX_ACOUNT_ID
替换第二列和第三列,以显示两次。每个SUPPLIER_ACCOUNT_ID
和BUYER_ACCOUNT_ID
都有唯一的XX_ACCOUNT_ID
和唯一的ACCOUNT_ID
。 XX_ACCOUNT_ID
属于表ACCOUNTS
,其中ACCOUNT_ID
(此列引用了SUUPLIER_ACCOUNT_ID & BUYER_ACCONT_ID
)和XX_ACCOUNT_ID
。我有点困惑,它需要嵌套的自联接还是多个内部联接?或子查询来解决这个问题?
答案 0 :(得分:4)
如果引用的表中始终存在R1.Supplier_Account_ID
和R2.Buyer_Account_ID
,则多个内部联接应该起作用。尝试这样的事情:
SELECT R1.RELATIONSHIP_ID, AcctSupp.XX_ACOUNT_ID, AcctBuyer.XX_ACOUNT_ID
FROM RELATIONSHIP R1
JOIN RELATIONSHIP R2 ON (R1.RELATIONSHIP_ID = R2.RELATIONSHIP_ID)
JOIN Accounts AcctSupp ON R1.SUPPLIER_ACCOUNT_ID = AcctSupp.Account_ID
JOIN Accounts AcctBuyer ON R2.BUYER_ACCOUNT_ID = AcctBuyer.Account_ID
ORDER BY SUPPLIER_ACCOUNT_ID;
如果引用的表中不存在值,则使用左连接:
SELECT R1.RELATIONSHIP_ID, AcctSupp.XX_ACOUNT_ID, AcctBuyer.XX_ACOUNT_ID
FROM RELATIONSHIP R1
JOIN RELATIONSHIP R2 ON (R1.RELATIONSHIP_ID = R2.RELATIONSHIP_ID)
LEFT JOIN Accounts AcctSupp ON R1.SUPPLIER_ACCOUNT_ID = AcctSupp.Account_ID
LEFT JOIN Accounts AcctBuyer ON R2.BUYER_ACCOUNT_ID = AcctBuyer.Account_ID
ORDER BY SUPPLIER_ACCOUNT_ID;
答案 1 :(得分:2)
也许我误解了这个问题,但我不明白为什么你需要自我加入:
SELECT R.Relationship_Id,
Supplier.xx_account_id sup_id,
Buyer.xx._account_id buy_id
FROM Relationship AS R
JOIN Accounts AS Buyer
ON R.Buyer_account_Id = Buyer.Account_Id
JOIN Accounts AS Supplier
ON R.Supplier_account_Id = Supplier.Account_Id