Reputation: 810
I’m using Active Record now. But it’s too slow if this code runs.
@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])
So, I’d like better performance with direct SQL query. But I have no idea how to write such complicated condition. How can I write SQL query to make this sophisticated and fast?
How do you write SQL query for this condition?
There are 4 tables such as below
User can bookmark Community by updating vote_flag of Votes table.
I’d like to fetch all the codes that belongs to communities that current_user has already bookmarked, and they have to be sorted by ‘user.active_at’ column.
Upvotes: 2
Views: 41
Reputation: 7288
You just need to JOIN
all those 4 tables and use ORDER BY
to sort the records..
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
OR, for more readability:
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
Hope it helps..
Upvotes: 1