SQLAlchemy:转换Self-Ref JOIN,COUNT,GROUP BY SELECT

时间:2013-03-07 17:14:06

标签: python sqlalchemy

我一直在努力争取一个SQL Select语句,该语句适用于等效的SQLAlchemy代码。它涉及两个表。

标签表

class Tags(Base):
    __tablename__ = 't_tags'
    uid                 = Column(Integer, primary_key=True)
    category            = Column(Enum('service', 'event', 'attribute', name='enum_tag_category'))
    name                = Column(String(32))

并将表格映射到他们的原始父母

class R_Incident_Tags(Base):
    __tablename__ ='r_incident_tags'
    incident_uid        = Column(String(48), ForeignKey('t_incident.uid'), primary_key=True)
    tag_uid             = Column(Integer, ForeignKey('t_tags.uid'), primary_key=True)

    tag = relationship("Tags", backref="r_incident_tags")

incident_uid是用于标识父级的唯一字符串。

我一直努力在SQLAlchemy中表示的SELECT如下

SELECT DISTINCT s.name, e.name, count(e.name)
    FROM "t_tags" AS s,
         "t_tags" AS e,
         "r_incident_tags" AS sr,
         "r_incident_tags" AS er
    WHERE   s.category='service' AND
            e.category='event' AND
            e.uid = er.tag_uid AND
            s.uid = sr.tag_uid AND
            er.incident_uid = sr.incident_uid
    GROUP BY s.name, e.name

任何帮助都会受到赞赏,因为我在一整天的努力之后甚至都没有接近工作。

最诚挚的问候!

1 个答案:

答案 0 :(得分:1)

这应该做的工作:

s = aliased(Tags)
e = aliased(Tags)
sr = aliased(R_Incident_Tags)
er = aliased(R_Incident_Tags)

qry = (session.query(s.name, e.name, func.count(e.name)).
        select_from(s, e, sr, er).
        filter(s.category=='service').
        filter(e.category=='event').
        filter(e.uid == er.tag_uid).
        filter(s.uid == sr.tag_uid).
        filter(er.incident_uid == sr.incident_uid).
        group_by(s.name, e.name)
        )

但您也可以使用基于relationship的{​​{1}}代替简单JOIN条款。