Post.includes(:user).where('sticky = true OR id in (select post_id from `feeds` where user_id = ? )',current_user.id).page(params[:page]).per(15)
意即
SELECT COUNT(*) FROM `posts` WHERE `posts`.`trashed` = 0 AND (sticky = true OR id in (select post_id from `feeds` where user_id = 1 ))
优化的第一步是得分析,使用
EXPLAIN
。用
OR
一般都可以使用UNION
来优化,如果子查询select post_id from
feedswhere user_id = 1
的结果会很大就不推荐使用IN
,用JOIN
可能会更好。