对从数据库中提取的线程注释进行分组

时间:2012-10-18 12:12:43

标签: python sql sqlalchemy

我正在按照以下教程显示数据库http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#adjacency-list-relationships

中的分层数据

到目前为止,我有下表

class Node(Base):
    __tablename__ = 'node'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('node.id'))
    data = Column(String(50))
    parent = relationship("Node", remote_side=[id])

以及mysql中的以下条目

id  parent_id   data
1   NULL            root
2   1 [->]          child1
3   1 [->]          child2
4   3 [->]          subchild1
5   3 [->]          subchild 2
6   1 [->]          child3
7   NULL            root2
8   NULL            root3
9   7 [->]          subchild0froot2
10  8 [->]          subchildofroot3
11  1 [->]          child4

我想以适合评论的格式检索数据,例如root - > child1 - > child2 - >(subchild1-> subchild2) - > child4

到目前为止,我已经能够通过此查询检索父项的子项

nodealias = aliased(Node)
qry = session.query(nodealias,Node).\
                join(nodealias, Node.parent).\
                filter(and_(Node.postid==45))



print qry
for x,y in qry:
    print x.data
    print y.data

    print "...."

And it displays

root
child1
....
root
child2
....
child2
subchild1
....
child2
subchild 2
....
root
child3
....
root
child4
....

我想以下列方式对此结果进行分组

root
....
child1
....
child2
subchild1
subchild 2
....
child3
....
child4
....

1 个答案:

答案 0 :(得分:0)

为了获得没有孩子的root,你应该使用OUTER JOIN而不是INNER JOIN。

要按子级分组您的孩子,您应该使用GROUP BY。

因此,您的查询将是:

  qry = session.query(nodealias,Node).\
        outerjoin(nodealias, Node.parent).\
        group_by(Node.parent).all()

然后,要在第一级叶子之间设置分隔符,则必须在迭代结果时对parent.id进行测试。不要忘记检查NoneType parent,因为你的结果集中包含了root。

  for parent, child in qry:
    if parent is None or parent.id != 1:
      print child.data
    else:
      print '...'
      print child.data

为了更好地使用3级叶子进行表示,您可以通过检查parent.id!= 2来应用类似的技术。

希望这会对你有所帮助。