Mysql 从大型数据集中过滤记录的最佳方法是什么
我在一个表中有大约500000个用户记录,另一个表包含其他用户专门阻止的用户的记录(即哪个用户阻止了哪个用户)。我使用以下查询来筛选当前用户的用户记录,这些记录不包含blocked表中的blocked usersMysql 从大型数据集中过滤记录的最佳方法是什么,mysql,sql,Mysql,Sql,我在一个表中有大约500000个用户记录,另一个表包含其他用户专门阻止的用户的记录(即哪个用户阻止了哪个用户)。我使用以下查询来筛选当前用户的用户记录,这些记录不包含blocked表中的blocked users SELECT * from demouser where id not in (select blockedid from demoblock where userid = 1 ) 速度很慢,执行查询大约需要2秒钟。有没有更有效的方法可以在不将500000个用户记录与阻塞表进行比较的
SELECT * from demouser where id not in (select blockedid from demoblock where userid = 1 )
速度很慢,执行查询大约需要2秒钟。有没有更有效的方法可以在不将500000个用户记录与阻塞表进行比较的情况下过滤记录,从而从结果中删除阻塞的用户?分别在
id
和userid
列上创建索引,这样子查询和查询都会运行得更快
此外,我建议稍作修改:
select * from demouser du
where not exists(select 1 from demouser
where blockedid = du.id
and userid = 1)
假设您的
demoblock
表不包含大量数据,您可以尝试使用内部联接。下面的查询示例:
SELECT * FROM demouser INNER JOIN demoblock ON demouser.id=demoblock.id WHERE demoblock.id=1;
我会将此写为不存在
:
select du.*
from demouser du
where not exists (select 1
from demoblock db
where db.blockedid = du.id and
db.userid = 1
);
对于此查询,您需要在demoblock(blockedid,userid)
上创建索引。我已经创建了索引,但查询速度仍然很慢,是否有其他方法不使用子查询,如JOIN、LEFT JOIN?@ArunJOIN
s会减慢查询速度您尝试过内部连接吗?