我有两个表(Loan_Contract
和Loan_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
。
如上所述,将结果归档的正确方法是什么?感谢。
答案 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))