I currently have two tables
question
--------
id
title, character varying
answer
--------
id
question_id
votes, integer
I use the following query to return me a list of questions with its corresponding array of votes:
SELECT question.id,
question.title,
ARRAY(SELECT votes
FROM answer
WHERE answer.question_id = question.id)
FROM question
ORDER BY question.id
The output looks like:
id | title | ?column?
----+----------+-----------------------------------------------------
100 | How to | {5,2,7}
101 | Where is | {0}
102 | What is | {1}
The above query can take close to 50s to run with hundred of thousands of questions where each question can have at least 5 answers. Is there a way to optimise the above?
votes
column of tableanswer
? Is it an array, or a single integer value? I assume it's a singleint
value. Your query doesn't work if it's an array.