考虑一个包含乒乓球比赛记录的数据库。 该数据库有两个表:
我们在sqlalchemy中描述这些表格如下:
class User(Base):
"""A user"""
__tablename__ = 'users'
name = Column(String(USER_NAME_LEN), primary_key=True)
class Game(Base):
"""A game"""
__tablename__ = 'games'
id = Column(Integer, primary_key=True)
playerA_id = Column(String(USER_NAME_LEN), ForeignKey('users.name'))
playerB_id = Column(String(USER_NAME_LEN), ForeignKey('users.name'))
playerA = relationship("User", backref=backref("games"),
foreign_keys=[playerA_id])
playerB = relationship("User", backref=backref("games"),
foreign_keys=[playerB_id])
scoreA = Column(Integer, nullable=False)
scoreB = Column(Integer, nullable=False)
我们想要生成一个玩家列表及其获胜总数。 执行此操作的SQL类似于(请参阅this other SO question)
SELECT winner, COUNT(*)
FROM
(
SELECT playerA_id AS winner FROM games
WHERE scoreA > scoreB
UNION ALL
SELECT playerB_id AS winner FROM games
WHERE scoreB > scoreA
)
GROUP BY winner
ORDER BY COUNT(*) DESC
使用sqlalchemy的ORM和查询如何完成?