I have a table where all comments are stored. Some comments are questions, other – answers.
So, my table looks like this:
id parent_id message is_answer answered
1 0 2x2 0 1
2 1 4 1 0
3 0 5x9 0 0
4 1 2x9 0 0
5 1 2x8 0 1
6 5 16 1 0
And as a result I’d like to get this table:
q_id q_message q_answer
1 2x2 4
3 5x9 NULL
4 2x9 NULL
5 2x8 16
So, I’d like to get all questions and answers to them, if they exist.
There is nothing that prevents you from joining a table to itself.
Note that this does not quite give the output you said you want… because it shows all answers to the question:
Your requested output only shows the answer “4” for question 1. I’m not sure if that was intentional on your part–if so, you’ll need some additional GROUP BY, or other logic, to filter out the answers you do not want displayed.