如何使用父/子关系对数据进行排序

时间:2013-06-30 21:46:28

标签: mysql

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

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 being replied to。现在我感到困惑的是,我想显示最近回复所订购的线程列表:

SELECT * FROM forum_threads
WHERE topic_id = :topic_id AND parent_id = 0
ORDER BY ??? DESC LIMIT :start, :display

不确定如何做到这一点?

3 个答案:

答案 0 :(得分:3)

如果父级不能拥有父级,则可以使用如下查询:

SELECT *
FROM forum_threads
ORDER BY
  CASE WHEN parent_id=0 THEN thread_id ELSE parent_id END DESC,
  Parent_id!=0,
  thread_id DESC

这将按降序列出所有主题,回复按最新主题排序。

答案 1 :(得分:2)

如果我正确理解了结构,那么回复就是那些parent_id指向“父”线程的thread_id的行。

如果是这种情况,像这样的自联接会起作用 - 请注意SELECT *必须去,因为(a)您从两个表中选择,因此*表示“所有行在两个表中“和(b)您需要GROUP BY个特定列:

SELECT
  parent.thread_id,
  parent.parent_id,
  parent.topic_id,
  parent.user_id,
  parent.title,
  parent.body,
  parent.create_date,
  MAX(reply.create_date) AS reply_date
FROM forum_threads parent
INNER JOIN forum_threads reply ON parent.thread_id = reply.parent_id
WHERE topic_id = whatever AND parent_id = 0
GROUP BY
  parent.thread_id,
  parent.parent_id,
  parent.topic_id,
  parent.user_id,
  parent.title,
  parent.body,
  parent.create_date
ORDER BY reply_date DESC

答案 2 :(得分:1)

这样的事情也可行:

SELECT * FROM forum_threads `t1`
WHERE topic_id = :topic_id AND parent_id = 0
ORDER BY (SELECT `create_date` FROM `forum_threads` WHERE `parent_id`=`t1`.`thread_id` ORDER BY `create_date` DESC LIMIT 1) DESC LIMIT :start, :display
如果你需要访问回复日期(我需要另一个子查询),Ed Gibbs的解决方案会更好,但如果你不需要它,这是一个更简单的解决方案(恕我直言)。