getting the last 15 dated items -- any way to optimize?
I have the following rails associations and named scopes:
class Person
has_many :schedulings, :include => :event
class Scheduling
belongs_to :person
belongs_to :event
named_scope :recent, :order => "date DESC", :limit => 15
class Event
has_many :schedulings
I need to get the 15 most recent schedulings for a person. Here is my rails controller code, and the SQL query it generates:
Person.find(1).schedulings.recent
----
SELECT * FROM `schedulings` WHERE (`schedulings`.person_id = 1) ORDER BY date DESC LIMIT 15
Unfortunately this query is getting slower as my table sizes grow (currently at about 10K schedulings and 3K people).
Can anyone give me advice on either A) ways to optimize the existing query, or B) a more direct way to query that information, perhaps with direct SQL instead of Rails Active Record?
My schedulings table has a foreign key index on person_id, and an index on date. I do not have a dual index on person_id and date. Typically a person will not have more than one sched开发者_StackOverflow社区uling per date.
I am comfortable with Rails but a relative novice at SQL.
Creating an index on person_id and date should speed your code up nicely.
Also SELECT *
is usually a bad idea speed wise.
Only select the fields you are actually going to use.
Especially if you have memo or blob fields in your table a select * will be slow as hell.
While you should have an index on the key to that table (IMO), more importantly for this case, you should have an index on the "date" field, as that's what you're ordering your results by...
I always like to use rails_footnotes while in development to see how well my queries (and how many) I'm needing for a given view
精彩评论