I got this query running perfectly already, but the problem is when my 4 tables get too big, it gets quite slow.
How can I optimize this?
SELECT
all_records.user_id,
users.NAME,
users.IMAGE
FROM (
SELECT user_id FROM comments
WHERE commentable_id = #{object.id}
AND commentable_type = '#{object.class.to_s}'
UNION ALL
SELECT user_id FROM hello
WHERE helloable_id = #{object.id}
AND helloable_type = '#{object.class.to_s}'
UNION ALL
SELECT user_id FROM foo
WHERE fooable_id = #{object.id}
AND fooable_type = '#{object.class.to_s}'
UNION ALL
SELECT user_id FROM bar
WHERE barable_id = #{object.id}
AND barable_type = '#{object.class.to_s}'
) AS all_records
INNER JOIN users ON users.id = all_records.user_id
GROUP BY
all_records.user_id,
users.NAME,
users.IMAGE
LIMIT 15
What the query should do is get the unique users that did something on the (4) tables (pardon the change of names of the tables). Even with the LIMIT 15
it still works slow because I think it still reads all the 4 tables. Am I doing this right or is there some way to optimize this?
For reference: I am using postgres and using rails but executing it in find_by_sql
.
EDIT
local postgres: 9.0.5; heroku postgres: 9.1