【问题标题】:SQLAlchemy find IDs from a list that don't exist in a tableSQLAlchemy 从表中不存在的列表中查找 ID
【发布时间】:2019-10-02 01:01:57
【问题描述】:

我有一个包含一些记录的表(每条记录都有一个 id - 主键)。现在我需要从指定的列表/集中选择表中不存在的所有 id。我正在使用 postgres 数据库和 sqlalchemy 作为 ORM。请建议必须执行这样的查询。

【问题讨论】:

    标签: database sqlalchemy


    【解决方案1】:

    对于一个非常大的集合可能效率不高,但演示的流程很简单:

    my_list = [1, 2, 3, 4, 5]
    missing_from_table = []
    for id in my_list:
        result = session.query(Model.id).get(id)  # result is a tuple
        if not result:
            missing_from_table.append(id)
    
    print(f'The following ids are not in the table: {missing_from_table}')
    

    另一种选择是:

    my_list = [1, 2, 3, 4, 5]
    all_ids = [r.id for r in session.query(Model.id).all()]
    missing_from_table = [id for id in my_list if id not in all_ids]
    

    【讨论】:

    • 这就像提取数据然后对其进行过滤。我对执行上述操作的查询很感兴趣。
    【解决方案2】:

    这是一个完全在数据库中运行的选项。它绕过了 ORM,但仍然利用 SQLAlchemy 的便利性进行会话和对象映射。

    from sqlalchemy import text
    
    my_list = [1, 2, 3, 4, 5, 6]
    query = text("""
        SELECT array_agg(id) 
        FROM unnest(:my_list) id 
        WHERE id NOT IN (
            SELECT 
                id 
            FROM 
                insert-table-name-here
        )
    """)
    
    # Belows assumes session is a defined SQLAlchemy database session
    
    missing_ids = session.execute(query, {'my_list': my_list}).scalar()
    print(f'The following ids from my_list are missing in table: {missing_ids}')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-03
      • 2018-05-30
      • 1970-01-01
      • 2020-02-11
      • 2019-01-09
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多