16

我有一个带计数的原始内部连接查询,直接写在 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";

如何使用普通的 SqlAlchemy 制作相同的内容,而不使用 Sqlalchemy connection.execute(sqlCode)

PS My 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)
4

1 回答 1

22

将其映射到 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

于 2013-11-09T00:01:44.307 回答