rails activerecord query join vs includes

时间:2015-07-16 00:17:07

标签: ruby-on-rails join activerecord include

我有以下型号

视频belongs_to:客户 消息属于:video,:customer,has_many:收件人通过:recipient_list RecipientList belongs_to:recipient,:message VideoActivity belongs_to:video,:message,:recipient

我需要对客户的最后100个收件人列表进行查询,该列表从与其关联的邮件的列中获取值,与该邮件关联的视频以及与该邮件和收件人绑定的视频活动。 / p>

我目前有这个丑陋的查询,但想知道如何加速它的最佳方法。从视频开始然后。包括消息,video_activities和收件人列表会更好吗?拥有大量视频的用户需要很长时间。

@videos = RecipientList.select("recipient_lists.*,
                                  COALESCE(sum(video_activities.duration_in_seconds),0) AS video_watched_duration_in_seconds,
                                  COALESCE(SUM(video_activities.video_watched_count),0) AS video_views,
                                  COALESCE(SUM(video_activities.response_count),0) AS responses,
                                  COALESCE(SUM(video_activities.email_opened_count),0) AS email_opens,
                                  CASE WHEN COUNT(video_activities.id) = 0 THEN 0 ELSE 1 END AS has_activity,
                                  MAX(video_activities.updated_at) AS last_activity,
                                  MAX(video_activities.email_opened_at) AS last_opened,
                                  MAX(video_activities.video_watched_at) AS last_watched,
                                  MAX(video_activities.responded_at) AS last_responded")
                     .joins("LEFT JOIN messages ON 52 = messages.customer_id
                             LEFT JOIN videos ON (messages.video_id = videos.id AND videos.template = false)
                             LEFT JOIN video_activities ON (videos.id = video_activities.video_id AND messages.id = video_activities.message_id AND recipient_lists.recipient_id = video_activities.recipient_id)")
                     .group("recipient_lists.id")
                     .where("messages.customer_id = 52")
                     .order("recipient_lists.created_at DESC")
                     .limit(100)
                     .load

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,这样做会更快吗?

T t(u);