This a simplified version of my SQL table for questions and answers, post_id is the primary key.
post_id | ref_post_id | title | date (unix timestamp)
1 | 0 | Title1 | 10
2 | 1 | | 20
3 | 0 | Title2 | 30
When ref_post_id is 0, that means it’s a question. When it is not 0 it’s an answer where the number corresponds to the question’s post_id. That means that the second row is an answer to the first row in my example above.
What I want to do is to get only the last row of every question. If the question does not have any answers I want the question row, but if it has answers I want the last answer but I want to join in the title that belongs to the question row.
I’ve googled and tried myself for a while now. Hopefully you understand my problem!
Thanks!
I would reccommend to split your table in two different tables, one for the questions and one for the answer.
However, the query you need could be written as this:
To select max date for every question/answer you have to group by
ref_post_id, except the case in whichref_post_id = 0where you have to group bypost_id, hence the IF.When you join the posts table with itself, using the subquery, you have to use the same trick.
EDIT: if you need to mark a question as deleted, then you have to remove all deleted questions and answers from the select above, and you have to use one more subquery to select only undeleted questions: