-3

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:

enter image description here

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?

4

2 回答 2

0

使用以下查询:

SELECT * FROM forum_threads
     WHERE topic_id = whatever AND parent_id = 0
     ORDER BY updated_date DESC limit 1;

这将为您提供最新的记录。

于 2013-07-04T07:15:24.887 回答
0

您可以简单地在 SQL 中执行此操作

SELECT ft.* FROM  forum_threads AS ft
JOIN forum_threads AS ft1 ON ft.id = ft1.thread_id
WHERE topic_id = whatever AND parent_id = 0
ORDER BY ft.create_date DESC
LIMIT 1
于 2013-07-04T07:39:55.973 回答