【问题标题】:SQLAlchemy - Select rows with the same column values, excluding those with values from different columnSQLAlchemy - 选择具有相同列值的行,不包括具有不同列值的行
【发布时间】:2014-12-08 15:10:58
【问题描述】:

我对 SQL / SQLAlchemy 缺乏经验,我正在尝试从名为 Event 的表中编写一个 SQLAlchemy 查询,其中包含如下数据:

我想选择 Type 等于“Viewed Tab”的行,但前提是不存在具有相同 Session 值且 Type 等于“Mobile View”的行。所以在上面的示例数据中,我希望查询返回 EventId 等于 150 和 154,但不是 147 的行。

谢谢。

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    假设表定义如下:

    class Event(Base):
        __tablename__ = 'events'
        EventId = Column(Integer, primary_key=True)
        Session = Column(Integer)
        Type = Column(String)
    

    产生期望结果的查询可以写成:

    viewed = aliased(Event, name='viewed')
    mobile = aliased(Event, name='mobile')
    qry = (session.query(viewed)
           .filter(viewed.Type == 'Viewed Tab')
           .outerjoin(mobile, and_(
               viewed.Session == mobile.Session,
               mobile.Type == 'Mobile View')
           )
           .filter(mobile.Session == None)
           )
    

    这将产生一个没有任何聚合的查询:

    SELECT  viewed."EventId" AS "viewed_EventId",
            viewed."Session" AS "viewed_Session",
            viewed."Type" AS "viewed_Type"
    
    FROM    events AS viewed
    
    LEFT OUTER JOIN
            events AS mobile
        ON  viewed."Session" = mobile."Session"
        AND mobile."Type" = 'Mobile View'
    
    WHERE   viewed."Type" = 'Viewed Tab'
        AND mobile."Session" IS NULL
    

    【讨论】:

      【解决方案2】:

      试试:

      select e.*
        from event e
        join (select eventid, session
                from event
               group by eventid, session
              having sum(case when type = 'Viewed Tab' then 1 else 0 end) > 0
                 and sum(case when type = 'Mobile View' then 1 else 0 end) = 0) v
          on e.eventid = v.eventid
      

      不过,我不确定 sql alchemy 有哪些语法限制。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-06
        • 2017-02-14
        • 2015-07-17
        • 2012-05-25
        • 2017-12-24
        • 1970-01-01
        • 2019-05-31
        • 2020-12-20
        相关资源
        最近更新 更多