SQLAlchemy查询和/或问题

2024-04-20 04:55:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个我正在尝试建立的查询。查询似乎是分部分工作的,查询的两个独立部分都返回正确数量的元素。但是,组合查询返回的结果集为空,这是不正确的。

注意:我知道查询1和查询2不需要和,但我想确保和查询1和查询2工作正常。

查询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)

谢谢你的帮助!


Tags: keynameidtrueascolumnintegerteam
2条回答

托尼,我从来不知道self_group(),非常棒!

特隆保罗, 可以使用self_group()添加paren around和clauseElement,例如:

query = session.query(Invoice).join(CustomerQuote).reset_joinpoint()

selections = [1,2,3,4,5,6]
select_ids = Invoice.invoice_id.in_(selections).self_group()
ands = and_(CustomerQuote.customer_id==33,  
       CustomerQuote.invoice_date>=low_date,
       CustomerQuote.invoice_date<=hi_date).self_group()

query = query.filter(or_(select_ors, ands))

SELECT invoice.invoice_id AS invoice_invoice_id, [etc etc....]
FROM invoice INNER JOIN customer_quote ON 
customer_quote.customer_quote_id = invoice.customer_quote_id 
WHERE (invoice.invoice_id IN (1,2,3,4,5)) OR 
      (customer_quote.customer_id = 33 AND 
       invoice.invoice_date >= '2012-01-01' AND 
       invoice.invoice_date <= '2012-12-31')

为了详细说明Tony的答案:self_group()对于分组“二进制”表达式以外的子句非常有用,它可以与任何子句元素一起使用。

我看到了你在SA 0.7.9上遇到的同样的问题

似乎发生的事情是括号并没有按您所希望的方式正确应用。我使用self_group()来实现这个功能,但问题是你不应该使用它。这是文件 self_group。我认为应该有一个比我更好的答案,但是,这应该让你去。

query = session.query(Lobby).filter(
    ((Lobby.id == Team.lobby_id) &
    (LobbyPlayer.team_id == Team.id) &
    (LobbyPlayer.player_id == player.steamid)).self_group() |
    ((Lobby.id == spectator_table.c.lobby_id) &
    (spectator_table.c.player_id == player.steamid)).self_group()).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 = ?)

相关问题 更多 >