我有一个正在尝试构建的查询。该查询似乎部分工作,查询的两个单独部分都返回正确数量的元素。但是,组合查询返回一个空结果集,这是不正确的。
注意:我知道查询 1 和 2 不需要 and_,但我想确保 and_ 按我的预期工作。
查询 1:
SQLAlchemy 查询
session.query(Lobby).filter( and_( Lobby.id == spectator_table.c.lobby_id, spectator_table.c.player_id == player.steamid ) ).all()
生成的 SQL
SELECT lobby.id AS lobby_id, lobby.name AS lobby_name, lobby.owner_id AS lobby_owner_id FROM lobby, spectator WHERE lobby.id = spectator.lobby_id AND spectator.player_id = ?
查询 2:
SQLAlchemy 查询
session.query(Lobby).filter( and_( Lobby.id == Team.lobby_id, LobbyPlayer.team_id == Team.id, LobbyPlayer.player_id == player.steamid ) ).all()
生成的 SQL
SELECT lobby.id AS lobby_id, lobby.name AS lobby_name, lobby.owner_id AS lobby_owner_id FROM lobby, team, lobby_player WHERE lobby.id = team.lobby_id AND lobby_player.team_id = team.id AND lobby_player.player_id = ?
组合查询:
SQLAlchemy 查询
session.query(Lobby).filter( or_( and_( Lobby.id == Team.lobby_id, LobbyPlayer.team_id == Team.id, LobbyPlayer.player_id == player.steamid ), and_( Lobby.id == spectator_table.c.lobby_id, spectator_table.c.player_id == player.steamid ) ) ).all()
生成的 SQL
SELECT lobby.id AS lobby_id, lobby.name AS lobby_name, lobby.owner_id AS lobby_owner_id FROM lobby, team, lobby_player, spectator WHERE lobby.id = team.lobby_id AND lobby_player.team_id = team.id AND lobby_player.player_id = ? OR lobby.id = spectator.lobby_id AND spectator.player_id = ?
模型
spectator_table = Table('spectator', Base.metadata,
Column('lobby_id', Integer, ForeignKey('lobby.id'), primary_key=True),
Column('player_id', Integer, ForeignKey('player.steamid'),
primary_key=True
),
)
class Lobby(Base):
__tablename__ = 'lobby'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
owner_id = Column(Integer, ForeignKey('player.steamid'), nullable=False,
unique=True
)
teams = relationship("Team", backref="lobby",
cascade='save-update,merge,delete'
)
spectators = relationship("Player", secondary=spectator_table)
class Team(Base):
__tablename__ = 'team'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
lobby_id = Column(Integer, ForeignKey('lobby.id'), nullable=False)
players = relationship("LobbyPlayer", backref="team",
cascade='save-update,merge,delete,delete-orphan'
)
class LobbyPlayer(Base):
__tablename__ = 'lobby_player'
team_id = Column(Integer, ForeignKey('team.id'), primary_key=True)
player_id = Column(Integer, ForeignKey('player.steamid'), primary_key=True)
player = relationship("Player", uselist=False)
cls = Column(Integer)
class Player(Base):
__tablename__ = 'player'
steamid = Column(Integer, primary_key=True)
谢谢您的帮助!