我试图运行这样的查询:
SELECT
comment_type_id, name, count(comment_type_id)
FROM
comments, commenttypes
WHERE
comment_type_id=commenttypes.id
GROUP BY
comment_type_id
如果没有comments
和commenttypes
之间对name
列的联接,我可以使用:
但是如果我尝试这样做,我会得到错误的结果:
session.query(Comment.comment_type_id, Comment.comment_type, func.count(Comment.comment_type_id)).group_by(Comment.comment_type_id).all()
我对结果有两个问题:
(1, False, 82920)
(2, False, 588)
(3, False, 4278)
(4, False, 104370)
问题:
False
不正确我的预期结果是:
(1, 'Comment Type 1', 13820)
(2, 'Comment Type 2', 98)
(3, 'Comment Type 2', 713)
(4, 'Comment Type 2', 17395)
如何调整命令以获取正确的name
值和正确的计数?在
我的模型定义如下:
class Comment(db.Model):
__tablename__ = 'comments'
id = Column(Integer, primary_key=True, unique=True)
comment_type_id = Column(Integer, ForeignKey('commenttypes.id'), nullable=False, index=True)
comment_type = relationship('CommentType', backref='comments')
class CommentType(db.Model):
__tablename__ = 'commenttypes'
id = Column(Integer, primary_key=True, unique=True)
name = Column(String(50, convert_unicode=True), nullable=False)
下面就可以了。您需要
join
两个模型,并将所有非聚合列添加到group_by
子句(我知道并非所有RDBMS都严格要求这样做,但我更希望安全)首先计算子查询中的计数,然后在最终查询中加入该计数。在
相关问题 更多 >
编程相关推荐