I'm storing threads for a forum with a parent / child relationship as follows:
CREATE TABLE forum_threads (
thread_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INTEGER UNSIGNED NOT NULL DEFAULT 0,
topic_id INTEGER UNSIGNED NOT NULL,
user_id INTEGER UNSIGNED NOT NULL,
title VARCHAR(100) NOT NULL,
body TEXT NOT NULL,
create_date DATETIME NOT NULL,
PRIMARY KEY (thread_id),
FOREIGN KEY (parent_id)
REFERENCES forum_threads(thread_id),
FOREIGN KEY (topic_id)
REFERENCES forum_topics(topic_id),
FOREIGN KEY (user_id)
REFERENCES users(user_id)
);
New threads have parent_id = 0
, whereas replies have parent_id = the thread_id being replied to
.
I want to select the most recently updated (replied to) threads and display the results in a table as follows:
How can I do this?
SELECT * FROM forum_threads
WHERE topic_id = whatever AND parent_id = 0
WHAT NEXT???
I'm not sure if this can be done with pure SQL, or if I should manipulate the results with PHP, or if I should try another approach all together?