gpt4 book ai didi

ruby-on-rails - 了解如何通过 Postgres/rails 解释数据优化查询

转载 作者:行者123 更新时间:2023-11-29 11:52:07 24 4
gpt4 key购买 nike

我有以下查询:

c = Invite.where(:invite_method => 'email', :email => email, :created_at => Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).count

此查询需要一些时间,因为该表有超过 100 万条记录。这是查询输出:

> invites_sent_today = Invite.where(:invite_method => 'email', :email => email, :created_at => Time.zone.now.beginning_of_day..Time.zone.now.end_of_day).exp 

Invite Load (62.3ms) SELECT "invites".* FROM "invites" WHERE "invites"."invite_method" = 'email' AND "invites"."email" = 'santa@site.com' AND ("invites"."created_at" BETWEEN '2013-01-20 00:00:00.000000' AND '2013-01-20 23:59:59.999999')

EXPLAIN (2.2ms) EXPLAIN SELECT "invites".* FROM "invites" WHERE "invites"."invite_method" = 'email' AND "invites"."email" = 'santa@site.com' AND ("invites"."created_at" BETWEEN '2013-01-20 00:00:00.000000' AND '2013-01-20 23:59:59.999999')

=> EXPLAIN for:

SELECT \"invites\".*
FROM \"invites\"
WHERE \"invites\".\"invite_method\" = 'email'
AND \"invites\".\"email\" = 'santa@site.com'
AND (\"invites\".\"created_at\"
BETWEEN '2013-01-2000:00:00.000000'
AND'2013-01-20 23:59:59.999999'
;

QUERY PLAN\n------------------------------------------------------------------------------------------------------------------------------------------------------------------\n
Index Scan using index_invites_on_created_at on invites (cost=0.00..17998.11 rows=2 width=129)\n
Index Cond: ((created_at >= '2013-01-20 00:00:00'::timestamp without time zone) AND (created_at <= '2013-01-20 23:59:59.999999'::timestamp without time zone))\n
Filter: (((invite_method)::text = 'email'::text) AND ((email)::text = 'santa@site.com'::text))\n(3 rows)\n"

关于如何提高此查询性能的任何建议?谢谢

最佳答案

按照 Igor 的建议,尝试复合索引:

CREATE INDEX index_invites_email_created_at on invites(email,created_at);

关于ruby-on-rails - 了解如何通过 Postgres/rails 解释数据优化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14428547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com