【问题标题】:How to convert this SQL Query to SQLAlchemy如何将此 SQL 查询转换为 SQLAlchemy
【发布时间】:2018-09-30 05:40:20
【问题描述】:

我在将此 SQL 查询转换为 SQLAlchemy 时遇到问题

SELECT Recipe.id, Recipe.name, AVG(Rating.rating) AS ar FROM Recipe LEFT OUTER JOIN Rating ON Recipe.id = Rating.recipe_id GROUP BY Recipe.id ORDER BY Recipe.id ASC;

我目前有:

session.query(Recipe,func.avg(Rating.rating).label('average')).outerjoin(Rating).filter(Recipe.id == Rating.recipe_id).group_by(Recipe.id).all()

但这会返回与此类似的内容,但缺少没有任何评级的元素:

 id |       name       |         ar
----+------------------+--------------------
  1 | First Response   | 4.0000000000000000
 34 | First Response 2 | 3.0000000000000000

当命令行中的 PostgreSQL 查询返回时:

 id |       name       |         ar
----+------------------+--------------------
  1 | First Response   | 4.0000000000000000
 34 | First Response 2 | 3.0000000000000000
 35 | First Response 2 |
 36 | First Response 2 |

这些是我的模型:

class Recipe(Base):
    __tablename__ = 'recipe'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    prep_time = Column(Integer)
    difficulty = Column(Integer)
    vegeterian = Column(Boolean)
    user_id = Column(Integer, ForeignKey('user.id'))
    ratings = relationship("Rating")

    def __repr__(self):
        return "<Recipe(name='{}', prep_time='{}', difficulty='{}', vegeterian='{}', user='{}')>".format(
            self.name, self.prep_time, self.difficulty, self.vegeterian, self.user_id
        )

class Rating(Base):
    __tablename__ = 'rating'
    id = Column(Integer, primary_key=True)
    recipe_id = Column(Integer, ForeignKey('recipe.id'))
    rating = Column(Integer)

    def __repr__(self):
        return "<Rating(name='{}', rating='{}')>".format(self.recipe.name, self.rating)

任何帮助将不胜感激!非常感谢。

【问题讨论】:

    标签: python sql python-3.x postgresql sqlalchemy


    【解决方案1】:

    删除

    filter(Recipe.id == Rating.recipe_id)
    

    因为外连接已经根据模型之间的外键关系生成了正确的 ON 子句。过滤器表达式被添加到 WHERE 子句中,对于没有评级的行会导致 UNKNOWN,因此它们会从结果中删除。

    【讨论】:

    • 非常感谢!有效。我当时并没有意识到这一点。非常感谢您的快速回复。
    猜你喜欢
    • 2017-04-25
    • 2019-03-20
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2016-01-23
    相关资源
    最近更新 更多