繁体   English   中英

SQLAlchemy在子代中查找所有重复项

[英]SQLAlchemy find all duplicates in children

我一直在寻找解决方案,但是在使用SQLAlchemy查找重复项时找不到任何东西。

我有一个父子类型关系,我希望在特定列的子项中找到所有重复项。

我尝试遍历每个父级并依靠该列,但这给了我毫无意义的结果。

parents = session.query(parent).all()
for parent in parents:
    dups = session.query(child).filter_by(parentid=parent.id).group_by(child.foo_column).count()
    if dups > 0:
        # do action on duplicates

如何获得重复的子代,或者甚至没有一个查询可以返回所有重复的子代?

编辑:表定义:

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

class child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parentid = Column(Integer, ForeignKey('parent.id'))
    foo_column = Column(Integer, ForeignKey('foo.id'))

    parent = relationship('parent',
                            backref=backref('children'))

    foo = relationship('foo')

我感兴趣的foo_column仅包含整数id,因此将在foo1.id == foo2.id地方重复。

您要实现的目标需要自我加入。 想想您将如何在SQL中执行此操作。 您的查询将类似于:

SELECT child_1.id as dup1, child_2.id as dup2
FROM child as child_1 JOIN child as child_2 
     ON child_1.parentid = child_2.parentid
WHERE child_1.foo_column = child_2.foo_column;

将其转换为SQL Alchemy很简单:

child_2 = aliased(child)
dups = session.query(child).
               join(child_2, child.parentid == child_2.parentid).
               filter(child.foo_column == child_2.foo_column).
               with_entities(child.id.label('dup1'), child_2.id.label('dup2'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM