2

我正在尝试在 SQLAlchemy 中进行以下连接

select * from splits s
join transactions t on t.guid = s.tx_guid
join accounts a on a.guid = s.account_guid
left join splits s2 on s2.tx_guid = t.guid
join accounts a2 on a2.guid = s2.account_guid
where a.name = 'Checking Account' and t.post_date > '2012-02-29'
order by t.post_date desc

使用这些模型

class Account(db.Model):
    __table__ = db.Table('accounts', db.metadata, autoload=True, autoload_with=db.engine)
    splits = db.relationship('Split', backref='account')

class Transaction(db.Model):
    __table__ = db.Table('transactions', db.metadata, autoload=True, autoload_with=db.engine)
    splits = db.relationship('Split', backref='transaction')

class Split(db.Model):
    __table__ = db.Table('splits', db.metadata,
                          db.Column('tx_guid', db.VARCHAR, db.ForeignKey('transactions.guid')),
                          db.Column('account_guid', db.VARCHAR, db.ForeignKey('accounts.guid')),
                          autoload=True, autoload_with=db.engine)

我做到了这一点,但现在我被困住了

q = Split.query.join(Transaction). \
                join(Account). \
                options(db.joinedload(Split.transaction)). \
                options(db.joinedload(Split.account)). \
                filter(Account.name == 'Checking Account'). \
                filter(Transaction.post_date > date(2012, 02, 29)). \
                order_by(db.desc(Transaction.post_date))

我如何将 join transactionssplits 分开,然后将那些splitsaccounts分开,即上面查询的最后两个联接?

4

1 回答 1

2

当你想在一个查询中多次引用同一个表时,你需要使用aliased()构造:

s = db.aliased(Split)
a = db.aliased(Account)
q = db.session.query(Split).\
    options(joinedload(Split.transaction)).\
    options(joinedload(Split.account)).\
    join(Transaction).\
    join(Account).\
    outerjoin(s, Transaction.splits).\
    join(a, a.guid == s.account_guid).\
    filter(Account.name == 'Checking Account').\
    filter(Transaction.post_date > date(2012, 2, 29)).\
    order_by(Transaction.post_date.desc())

在混合 INNER和OUTER 连接时要小心

于 2013-07-20T11:23:19.743 回答