我现在正在使用Active Record。但是如果这个代码运行的话,它太慢了。
@communities = current_user.get_up_voted(Community)
@codes = Code.includes(:user).where(:community_id => @communities.collect(&:id)).order("users.active_at DESC").page(params[:page])
所以,我想通过直接SQL查询获得更好的性能。但我不知道如何写出如此复杂的条件。 如何编写SQL查询以使其更加复杂和快速?
如何为这种情况编写SQL查询?
有4个表,如下面的
用户可以通过更新投票表的vote_flag为社区添加书签。
我想获取属于current_user已添加书签的社区的所有代码,并且必须按'user.active_at'列进行排序。
答案 0 :(得分:1)
您只需要JOIN
所有这4个表并使用ORDER BY
对记录进行排序..
SELECT * FROM Users, Votes, Community, Codes
WHERE Codes.community_id = Community_id
AND Codes.user_id = Users.id
AND Votes.votable_id = Community.id
AND Votes.voter_id = Users.id
AND Votes.votable_id = Codes.community_id
AND Votes.voter_id = Codes.user_id
AND Votes.vote_flag = 1
ORDER BY USERS.active_at ASC
或者,为了更具可读性:
SELECT * FROM Users
JOIN Codes ON Codes.user_id = Users.id
JOIN Community ON Codes.community_id = Community.id
JOIN Votes ON Votes.votable_id = Codes.community_id AND Votes.voter_id = Codes.user_id
WHERE vote_flag = 1
ORDER BY USERS.active_at ASC
希望有所帮助......