postgres递归查询
示例
1 2 3 4 5 6 7 8 9 | WITH RECURSIVE t AS ( select * from danger_classify where parent_id = -1 UNION ALL select dc.* from danger_classify dc, t where dc.parent_id = t.id ) SELECT * FROM t; |
运行过程
包含recursive的关键字,需要有union或者union all
1.计算非递归内容,放入工作表;
2.只要工作表不为空计算一下内容:
1) 计算递归项,用自身的递归取代工作表。去掉重复内容,之前的内容。剩下的内容进行递归,并且放入中间表
2) 用中间标内容替换工作标,并且清空中间表.
解析为树形数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | def get_tree_data(): sql = ''' WITH RECURSIVE t AS ( select * from danger_classify where parent_id = -1 UNION ALL select dc.* from danger_classify dc, t where dc.parent_id = t.id ) SELECT * FROM t; ''' trees = [] temp = {} for row in database.db.query(sql): tree = { "id" : int (row. id ), "data" : row, "children" : []} temp[row. id ] = tree[ "children" ] if row.parent_id is None : trees.append(tree) else : temp[row.parent_id].append(tree) return trees |
原理是借用了引用的特性。在temp中平铺所有的节点,在trees中保存结果。在temp中操作来改变trees中的结构,形成树状.