与SqlAlchemy的内部联接

时间:2013-11-07 16:53:17

标签: sql postgresql sqlalchemy

我有一个带有计数的原始内连接查询,直接写在Postgres SQL上:

    SELECT "films"."id" AS "megaId", 
           COUNT("filmComments"."id") AS "numOfComments" 
      FROM "films"
INNER JOIN "filmComments" 
        ON ("films"."id" = "filmComments"."filmId") 
  GROUP BY "films"."id";

如何在没有connection.execute(sqlCode)的情况下使用普通的SqlAlchemy进行相同的操作?

P.S。我的SqlAlchemy表类:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String, Date, Float

class Film(Base):
    __tablename__ = "films"
    id = Column(Integer, primary_key = True)
    name = Column(String)
    rating = Column(Float)
    marksCount = Column(Integer)
    commentsCount = Column(Integer, index=True)


class FilmComment(Base):
    __tablename__ = "filmComments"
    id = Column(Integer, primary_key = True)
    filmId = Column(Integer, index=True)
    rating = Column(Integer, index=True)
    text = Column(String)
    votesUp = Column(Integer)
    votesDown = Column(Integer)
    userId = Column(Integer)
    date = Column(Date)

1 个答案:

答案 0 :(得分:8)

将其映射到SQLAlchemy应该非常简单。我没有考虑别名,原因显而易见。

from sqlalchemy import func

megaId, numOfComments = (session.query(Film.id, func.count(FilmComment.id))
                                .join(FilmComment, Film.id == FilmComment.filmId)
                                .group_by(Film.id).first())

这应该有效。如果将on声明为外键,则不需要显式FilmComment.filmId子句。