如何使用父/子关系选择和排序数据

时间:2013-07-04 06:59:21

标签: php mysql forum

我正在为具有父/子关系的论坛存储线程,如下所示:

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)
);

新帖子有parent_id = 0,而回帖有parent_id = the thread_id being replied to

我想选择最近更新(回复)的主题并在表格中显示结果,如下所示:

enter image description here

我该怎么做?

SELECT * FROM forum_threads
WHERE topic_id = whatever AND parent_id = 0
WHAT NEXT???

我不确定是否可以使用纯SQL来完成,或者我是否应该使用PHP操作结果,或者我是否应该尝试其他方法?

2 个答案:

答案 0 :(得分:0)

使用以下查询:

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

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

答案 1 :(得分: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