问题描述
我在一个文本文件中有一个很大的ID列表(1000个)。我想从数据库中返回与这些ID对应的行。我该怎么办?
我当前的方法是简单地将整个列表粘贴到一个巨大的SQL查询中并运行它。它有效,但是我觉得必须有更好的方法。
解决方法
随着值列表越来越大,更好的解决方案是将其加载到表中,然后可以在查询中使用它。在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
语法接受许多选项来适应输入文件的格式-您可以阅读文档以获取更多信息。