我有一个具有enemy_onefight_idenemy_two的表。

问题是,有时enemy_two变为enemy_one,反之亦然。

我可以:

session.query(Fight.fight_id).filter(Fight.enemy_one=='Jack', Fight.enemy_two=='Fat Chinese').all()


然后:

session.query(Fight.fight_id).filter(Fight.enemy_one=='Fat Chinese', Fight.enemy_two=='Jack').all()


这样我就可以解决所有问题,但是有一种方法可以将这两个查询绑定在一起?

最佳答案

使用in_子句:

def get_fights(enemy_one, enemy_two):
    return (
        session
        .query(Fight)
        .filter(Fight.enemy_one.in_([enemy_one, enemy_two]))
        .filter(Fight.enemy_two.in_([enemy_one, enemy_two]))
        .filter(Fight.enemy_one != Fight_enemy_two)
    )


使用or_子句:

def get_fights(enemy_one, enemy_two):
    return (
        session
        .query(Fight)
        .filter(or_(
            and_(Fight.enemy_one == enemy_one, Fight.enemy_two == enemy_two),
            and_(Fight.enemy_one == enemy_two, Fight.enemy_two == enemy_one),
        ))
    )

关于python - SqlAlchemy如何查询列A == a和B == b和A == b和B == a,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41129518/

10-12 21:01