0

Setup

I have the following tables:

Questions
 - id      (INT)
 - quizId  (INT)
 - text    (TEXT)          
 - options (JSON[])      

Answers
 - id      (INT)
 - questionId (INT)
 - choice  (INT)

"options" is an array of JSON objects:

{"{\"text\": \"Text for option 1\", \"correct\": false}", "{\"text\": \"Text for option 2\", \"correct\": true}"}

Question

I would basically like to get the value of "correct", given "choice" (an index), after joining those two tables.

The pseudocode for what I'm trying to achieve would be:

select "Questions"."options"["Answers"."choice"] from <JOIN THOSE TABLES>;
4
  • 1
    How is this different from your previous question? Please avoid posting duplicates, instead you can wait for answers, or update your question to improve it somehow. Commented Jan 13, 2020 at 21:25
  • @GMB Well, I simplified it for myself and others by taking out the filter part. Seemed different enough. Commented Jan 13, 2020 at 21:27
  • 1
    I suppose I can delete the other Commented Jan 13, 2020 at 21:27
  • I suspect that proper sample data for both tables, along with the expected results (as tabular text), would make your question more appealing. Also your other question was showing your attemped SQL query, which is always a good thing; you might want to reincorporate it here. Commented Jan 13, 2020 at 21:29

1 Answer 1

1

Not just pseudocode, that's exactly how you write array subscripts. Now only the JOIN condition is missing:

SELECT "Questions"."options"["Answers"."choice"] AS choosen_answer_option
FROM "Questions" JOIN "Answers" ON ("Questions".id = "Answers"."questionId")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So the final part is that I need to get "correct" from those objects. I'm able to pull out the array item, but now I need to get the field from that item!
Use the json ->/->> operators for that, e.g. (options[choice]->>'correct')::boolean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.