python sqlalchemy不同的列值

时间:2016-03-14 15:01:55

标签: python sqlalchemy

我的SQLite数据库中有6个表,每个表有6列(Date, user, NormalA, specialA, contact, remarks)和1000多行。

如何使用sqlalchemy对Date列进行排序以查找重复日期,并删除该行?

3 个答案:

答案 0 :(得分:2)

假设这是你的模特:

class MyTable(Base):
    __tablename__ = 'my_table'
    id = Column(Integer, primary_key=True)
    date = Column(DateTime)
    user = Column(String)
    # do not really care of columns other than `id` and `date`
    # important here is the fact that `id` is a PK

以下是两种删除数据的方法:

  1. 查找重复项,将其标记为删除并提交事务
  2. 创建一个SQL查询,直接在数据库上执行删除。
  3. 对于他们两个,将使用辅助子查询:

    # helper subquery: find first row (by primary key) for each unique date
    subq = (
        session.query(MyTable.date, func.min(MyTable.id).label("min_id"))
        .group_by(MyTable.date)
    ) .subquery('date_min_id')
    

    选项-1:查找重复项,将其标记为删除并提交交易

    # query to find all duplicates
    q_duplicates = (
        session
        .query(MyTable)
        .join(subq, and_(
            MyTable.date == subq.c.date,
            MyTable.id != subq.c.min_id)
        )
    )
    
    for x in q_duplicates:
        print("Will delete %s" % x)
        session.delete(x)
    session.commit()
    

    选项-2:创建一个SQL查询,直接在数据库上执行删除

    sq = (
        session
        .query(MyTable.id)
        .join(subq, and_(
            MyTable.date == subq.c.date,
            MyTable.id != subq.c.min_id)
        )
    ).subquery("subq")
    
    dq = (
        session
        .query(MyTable)
        .filter(MyTable.id.in_(sq))
    ).delete(synchronize_session=False)
    

答案 1 :(得分:1)

Find duplicate values in SQL table的启发,这可能有助于您选择重复日期:

query = session.query(
    MyTable
).\
    having(func.count(MyTable.date) > 1).\
    group_by(MyTable.date).all()

如果您只想显示独特的日期;您可能需要distinct on

答案 2 :(得分:1)

虽然我喜欢使用SQLAlchemy的整个面向对象的方法,但有时我发现直接使用某些SQL更容易。 由于记录没有密钥,我们需要行号(_ROWID_)来删除目标记录,我认为API不提供它。

首先我们连接到数据库:

from sqlalchemy import create_engine
db = create_engine(r'sqlite:///C:\temp\example.db')
eng = db.engine

然后列出所有记录:

for row in eng.execute("SELECT * FROM TableA;") :
  print row

并显示日期相同的所有重复记录:

for row in eng.execute("""
  SELECT * FROM {table}
  WHERE {field} IN (SELECT {field} FROM {table} GROUP BY {field} HAVING COUNT(*) > 1)
  ORDER BY {field};
  """.format(table="TableA", field="Date")) :
  print row

现在我们确定了所有重复项,如果其他字段不同,则可能需要修复它们:

eng.execute("UPDATE TableA SET NormalA=18, specialA=20 WHERE Date = '2016-18-12' ;");
eng.execute("UPDATE TableA SET NormalA=4,  specialA=8  WHERE Date = '2015-18-12' ;");

最后保留第一个插入的记录并删除最近的重复记录:

print eng.execute("""
  DELETE FROM {table} 
  WHERE _ROWID_ NOT IN (SELECT MIN(_ROWID_) FROM {table} GROUP BY {field});
  """.format(table="TableA", field="Date")).rowcount

或者保留最后插入的记录并删除其他重复记录:

print eng.execute("""
  DELETE FROM {table} 
  WHERE _ROWID_ NOT IN (SELECT MAX(_ROWID_) FROM {table} GROUP BY {field});
  """.format(table="TableA", field="Date")).rowcount