自我加入不同的表

时间:2013-08-30 05:15:26

标签: sql oracle

我写了以下查询:

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. ACCOUNTACCOUNT_ID, XX_ACCOUNT_ID ....

并且到目前为止正确地给出了结果

result sampe

但是,我想要的更复杂。我需要使用列called XX_ACOUNT_ID替换第二列和第三列,以显示两次。每个SUPPLIER_ACCOUNT_IDBUYER_ACCOUNT_ID都有唯一的XX_ACCOUNT_ID和唯一的ACCOUNT_IDXX_ACCOUNT_ID属于表ACCOUNTS,其中ACCOUNT_ID(此列引用了​​SUUPLIER_ACCOUNT_ID & BUYER_ACCONT_ID)和XX_ACCOUNT_ID。我有点困惑,它需要嵌套的自联接还是多个内部联接?或子查询来解决这个问题?

2 个答案:

答案 0 :(得分:4)

如果引用的表中始终存在R1.Supplier_Account_IDR2.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