Database 执行PostgreSQL查询速度慢,原因不明
我在rails中有以下查询,它使用PostgreSQL 9作为数据库Database 执行PostgreSQL查询速度慢,原因不明,database,performance,postgresql,Database,Performance,Postgresql,我在rails中有以下查询,它使用PostgreSQL 9作为数据库 @user_random = User.where(:id => User.where(:pubic_profile_visible => true).order('random()').limit(1).select(:id).collect(&:id)).first 然后在数据库服务器上: 解释计划 Query plan Limit (cost=48655.53..48655.53 rows=1
@user_random = User.where(:id => User.where(:pubic_profile_visible => true).order('random()').limit(1).select(:id).collect(&:id)).first
然后在数据库服务器上:
解释计划
Query plan Limit (cost=48655.53..48655.53 rows=1 width=4)
Query plan -> Sort (cost=48655.53..50880.35 rows=889930 width=4)
Query plan Sort Key: (random())
Query plan -> Seq Scan on users (cost=0.00..44205.88 rows=889930 width=4)
Query plan Filter: (pubic_profile_visible AND (deleted_at IS NULL))
有没有关于这会造成瓶颈的建议?谢谢你,Like@wildplasser说这个查询正是你要求它做的 如果不获取所有800000行,生成一个随机数,然后对它们进行排序,它就无法为“LIMIT 1”选择最低的random() 试试谷歌搜索“postgresql选择随机行”,你会发现半打有用的stackoverflow问题,还有一个指向depesz.com上一篇旧博文的链接,其中包括各种选项:
好吧,看来您正在对random()上的800K条记录进行排序,以便只选择一条。请注意,在9.5中,您现在可以在FROM子句中使用TABLESAMPLE:和