【问题标题】:Get subset of rows based on a list of primary keys in file根据文件中的主键列表获取行子集
【发布时间】:2020-08-25 22:44:04
【问题描述】:

我在一个文本文件中有一个大 (1000s) 的 ID 列表。我想从我的数据库中返回与这些 ID 对应的行。我该怎么做?

我当前的方法是简单地将整个列表粘贴到一个巨大的 SQL 查询中并运行它。它有效,但我觉得必须有更好的方法。

【问题讨论】:

    标签: mysql sql csv join subquery


    【解决方案1】:

    随着值列表越来越大,更好的解决方案是将其加载到表中,然后您可以使用它进行查询。在 MySQL 中,load data statement 语法对此非常方便。

    考虑如下:

    create temporary table all_ids (id int);
    load data infile 'myfile.txt' into table all_ids;
    create index idx_all_ids on all_ids(id);  -- for performance
    
    select t.*
    from mytable t
    where exists (select 1 from all_ids a where a.id = t.id)
    

    load data 语法接受许多选项来适应输入文件的格式 - 您可以阅读文档以获取更多信息。

    【讨论】:

    • 这与我最终做的类似,只是我使用了连接。
    猜你喜欢
    • 2010-10-08
    • 2020-09-09
    • 2015-11-21
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多