与SqlAlchemy的内部联接

编程入门 行业动态 更新时间:2024-10-23 03:24:41
本文介绍了与SqlAlchemy的内部联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a raw inner join query with counting, written directly on 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在没有 connection.execute的情况下进行相同的操作(sqlCode)?

How can I make the same, using normal SqlAlchemy, without connection.execute(sqlCode)?

PS我的SqlAlchemy表类:

P.S. My SqlAlchemy table classes:

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)

推荐答案

将其映射到SQLAlchemy应该非常简单。出于明显的原因,我没有考虑别名。

Mapping that to SQLAlchemy should be quite straightforward. I'm not considering the aliases, for obvious reasons.

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())

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

This should work. The explicit on clause wouldn't be needed if FilmComment.filmId were declared as a foreign key.

更多推荐

与SqlAlchemy的内部联接

本文发布于:2023-10-25 08:17:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SqlAlchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!