gpt4 book ai didi

python - 获取与同一个表中的父元素相关的子元素

转载 作者:行者123 更新时间:2023-11-29 14:15:37 25 4
gpt4 key购买 nike

我有以下数据库架构

class posts(Base):
__tablename__ = 'xposts'
id = Column(Integer, primary_key=True)



class Comments(Base):
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
comment_parent_id=Column(Integer,unique=True)
#comment_id fetches comment of a comment ie the comment_parent_id
comment_id=Column(Integer,default=None)
comment_text=Column(String(200))

数据库中的值为

1   12  NULL    Hello First comment
2 NULL 12 First Sub comment

我想使用 sqlalchemy 获取帖子的所有评论和子评论并到目前为止

qry=session.query(Comments).filter(Comments.comment_parent_id!=None)
print qry.count()

有没有一种方法可以获取查询中评论的所有子评论,我在同一个表(评论)上尝试过外连接,但它看起来很愚蠢并且失败了。

最佳答案

您在 sqlalchemy 查询中使用了 all() 函数,之后您可以使用 count 和 len 来查找数据库中的总行数。因为此查询提供了二维列表结果。

qry=session.query(Comments).filter(Comments.comment_parent_id!=None).all()

len(qry)

关于python - 获取与同一个表中的父元素相关的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12753049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com