Sqlalchemy cte递归查询

db:MariaDB
MariaDB数据库管理系统是MySQL的一个分支

版本:5.7.36-log

select version()

代码示例

from sqlalchemy.orm import aliased


hierarchy = db.query(DepartmentModel) \
    .filter(DepartmentModel.parent_id.in_(d_ids)) \
    .cte(name="hierarchy", recursive=True)
parent = aliased(hierarchy, name="p")
children = aliased(DepartmentModel, name="c")
hierarchy = hierarchy.union_all(
    db.query(children)
    .filter(children.parent_id == parent.c.id))
data = db.query(DepartmentModel).select_entity_from(hierarchy).all()

你可能感兴趣的:(python,python)