I have two tables: question and answer.
Here is a simplified version of the question table's schema:
question_id integer PRIMARY KEY
question_title varchar(250)
answers_id SERIAL UNIQUE
Here is a simplified version of the answer table's schema:
answer_id integer REFERENCES question (answers_id)
answer_text varchar(500)
is_top_answer boolean
I would like to accomplish three tasks in a single query:
- Select a row from the question table based off of a parameter that contains a question_id.
- Join exactly one row from the answer table with the row retrieved from the question's table in step 1 of the query where the two following conditions are satisfied by a row in the answer table: 1. the is_top_answer is true and 2. the answer_id equals the answers_id of the row retrieved from the question table in step 1 of the query.
- Join a variable amount of rows from the answer table with the row retrieved from the question's table in step 1 of the query where the answer table's answer_id matches the answers_id of the row retrieved from the question table in step 1 of the query.
I have populated the question and answer tables with the following SQL statements:
insert into question values (1, 'Where is the best sushi restaurant?', 10);
insert into answer values (10, 'In California', 'false');
insert into answer values (10, 'In Seattle', 'true');
insert into answer values (10, 'In New York', 'false');
If I were to query the question table with a parameter that represents a question_id held in the question table, I would expect the following single row as a result:
question_id | question_title | answers_id | answer_text | is_top_answer | answer_text | is_top_answer | answer_text | is_top_answer |
-------------+-------------------------------------+------------+---------------+----------------+---------------+----------------+---------------+----------------+
1 | Where is the best sushi restaurant? | 10 | In Seattle | f | In California | f | In New York | f |
Does anyone have any suggestions for accomplishing this query?