0

我写了以下查询:

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....

并给出正确的结果

结果样本

但是,我想要的更复杂。我需要将第二列和第三列替换called XX_ACOUNT_ID为要显示两次的列。每一个都有一个独特的SUPPLIER_ACCOUNT_ID和独一无二的。属于有(从本列引用)和的表。我有点困惑,它需要嵌套自联接还是多个内部联接?或子查询来解决这个问题?BUYER_ACCOUNT_IDXX_ACCOUNT_IDACCOUNT_IDXX_ACCOUNT_IDACCOUNTSACCOUNT_IDSUUPLIER_ACCOUNT_ID & BUYER_ACCONT_IDXX_ACCOUNT_ID

4

2 回答 2

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;
于 2013-08-30T05:23:49.330 回答
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
于 2013-08-30T05:26:15.987 回答