SqlAlchemy:加入两个不等于条件的表

时间:2017-12-28 17:35:16

标签: python-2.7 sqlalchemy

我有两个表(Loan_ContractLoan_Amend),它们具有相同的列LoanID。我的目的是,只有当表Loan_Contract中不存在表Loan_Amend时才能获取所有数据。

所以我尝试了如下查询:

db.session.query(
                Loan_Contract.ID,
                Loan_Contract.Currency,
                Loan_Contract.DisbursedAmount
            ).\
            join(Loan_Amend,Loan_Amend.LoanID != Loan_Contract.ID).\
            all()

db.session.query(
                Loan_Contract.ID,
                Loan_Contract.Currency,
                Loan_Contract.DisbursedAmount
            ).\
            join(Loan_Amend,Loan_Amend.LoanID == Loan_Contract.ID).\
            filter(Loan_Contract.ID != Loan_Amend.LoanID).\
            all()

但是,上述任一查询都会返回Loan_Contract中的所有记录,即使LoanID中存在Loan_Amend

如上所述,将结果归档的正确方法是什么?感谢。

1 个答案:

答案 0 :(得分:2)

要获取所有Loan_Contract行没有引用任何Loan_Amend行,您需要使用LEFT JOIN

SELECT * FROM Loan_Contract LEFT JOIN Loan_Amend ON Loan_Contract.ID = Loan_Amend.LoanID
WHERE Loan_Amend.LoanID IS NULL;

使用SQLAlchemy:

session.query(Loan_Contract) \
       .outerjoin(Loan_Amend, Loan_Contract.ID == Loan_Amend.LoanID) \
       .filter(Loan_Amend.LoanID.is_(None))