python - 如何按连接数对查询进行排序

标签 python mysql sql sqlalchemy

ParentChild 表与 parent_uuid ForeignKey 属性链接:

from sqlalchemy.ext.declarative import declarative_base
import uuid

Base = declarative_base()
class Parent(Base):
    __tablename__ = 'parents'
    uuid = Column(String(64), primary_key=True, unique=True)
    def __init__(self):  
        self.uuid = uuid.uuid4()   

class Child(Base):
    __tablename__ = 'children'
    uuid = Column(String(64), primary_key=True, unique=True)
    parent_uuid = Column(String(64), ForeignKey('parents.uuid'))
    def __init__(self, parent_uuid=None):  
        self.uuid = uuid.uuid4()   
        self.parent_uuid = parent_uuid

for 循环用于声明Parent 对象。使用 random.randomint()) 每个 parent 都链接了随机数量的 child :

for i in range(25):
    parent = Parent()
    session.add(parent)
    session.commit()
    parent_uuid = parent.uuid 
    for i in range(random.randint(0, 10)):
        child = Child(parent_uuid=parent_uuid)
        session.add(child)
        session.commit()

如何查询所有 Parent 实体,这些实体由多个链接的 Children 排序。 Parent 拥有最多的 children 应该是列表中的第一个。我可以使用 order_by() 函数按 uuid 属性排序:

session.query(Parent).order_by(desc(Parent.uuid)).all()

但是这里,需要先计算 child 的数量。如何按尚未计算的值排序?

最佳答案

您可以使用 partition by 和 count 函数,该函数将添加与其 parent 相关的每个 child 的计数。然后您可以使用该列进行排序。

看起来像这样:

from sqlalchemy import desc, func

query = session.query(Parent, Child, func.count().over(partition_by=Parent.uuid)
.label('children_count'))
.filter(Child.parent_uuid == Parent.uuid)
.order_by(desc('children_count'))
print(query)

这将产生以下 sql:

SELECT parents.uuid AS parents_uuid, children.uuid AS children_uuid,
children.parent_uuid AS children_parent_uuid, 
count(*) OVER (PARTITION BY parents.uuid) AS children_count
FROM parents, children
WHERE children.parent_uuid = parents.uuid ORDER BY children_count DESC

它为您提供按相关 child 记录的最高计数排序的 parent 和 child 。

关于python - 如何按连接数对查询进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657823/

相关文章:

python - 如何用装饰器绕过python函数定义?

python类变量按值查找

mysql - oracle sql开发人员不存储unicode

MySQL 在另一个查询中使用查询

php - 具有定义的日期间隔的 MySQL 查询行

sql - 查找与SQL中的键值对匹配的案例

python - 值在图中看不清楚

python - 连接到我自己笔记本电脑上树莓派上运行的 MySQL

sql - 根据计算值选择,优化

mysql - SQL Select 查询以选择日期之间的数据,其中起始日期月份高于截止日期月份和年份差异> 1