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 ))
@Mr_Jing 说的都很对,接着他的说,最好不用子查询,变成where条件,转换不成where的话转换成join, 如果一行的数据比较大不推荐count(*) 最好count(主键),尤其是数据库引擎为InnoDB的时候。再次强调要用EXPLAIN来分析
优化的第一步是得分析,使用EXPLAIN
。
用OR
一般都可以使用UNION
来优化,如果子查询select post_id from
feedswhere user_id = 1
的结果会很大就不推荐使用IN
,用JOIN
可能会更好。
id in (select post_id from `feeds` where user_id = 1 )
不清楚feeds有多大,但第一眼看到你说优化的话,可能目标就是in,数据多的话你要尽量的避免去in。
可以考虑冗余字段,用join等等办法……