SQLAlchemy - 选择具有相同列值的行,不包括具有不同列值的行

时间:2014-10-13 23:19:52

标签: python sql sqlalchemy

我对SQL / SQLAlchemy缺乏经验,并且我试图从名为Event的表中编写一个SQLAlchemy查询,其数据如下:

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

谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

尝试:

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炼金术的语法限制是什么。