In a database structure for Question/Answer/Comment like stachexchange projects, the database schema can be three columns connected with FKs. This seems to be ideal, but I wonder what is the most efficient query to retrieve the data for a question. Answers will be simply retrieved and listed by a WHERE clause of the question_id.
My question is how to list comments nested under its corresponding answer? I am dealing with the PHP while loop to list answers and sub-lists of comments.
A very basic structure in my mind. A purpose of my question is to find idea database structure too; thus, this is merely a suggestion.
CREATE TABLE questions (
question_id int(11) NOT NULL AUTO_INCREMENT,
title varchar(255),
content text,
PRIMARY KEY (question_id);
CREATE TABLE answers (
answer_id int(11) NOT NULL AUTO_INCREMENT,
question_id int(11) REFERENCES questions(question_id),
content text,
PRIMARY KEY (answer_id);
CREATE TABLE comments (
coment_id int(11) NOT NULL AUTO_INCREMENT,
question_id int(11) REFERENCES questions(question_id),
answer_id int(11) REFERENCES answers(answer_id),
content text,
PRIMARY KEY (coment_id);
Assuming a Table structure as follows(simplified)
fQID = foreign Key for Questions Table
fAID = foreign key for Answers table
Following query will select all the comments for a particular question
Following query will select comments accourding to the Answer ID
Edit:
For Nesting comments under answers, use something like this (you will need to modify this, this is very rough)