【问题标题】:SQLAlchemy find all duplicates in childrenSQLAlchemy 查找子项中的所有重复项
【发布时间】:2015-08-29 13:01:10
【问题描述】:

我一直在寻找解决方案,但在使用 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 的位置。

【问题讨论】:

  • 您能否提供您的表定义以及您的重复项是什么?

标签: python sqlalchemy


【解决方案1】:

您要实现的目标需要自我加入。想想你将如何在 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'))

【讨论】:

  • with_entities 部分给了我一个错误,但除此之外它工作得很好。谢谢!
  • 我知道那里出了什么问题 - with_entities 需要 *entities arg。修好了。
猜你喜欢
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2020-03-31
相关资源
最近更新 更多