SQL查询选择所有论坛帖子,但是按最新活动线程排序

时间:2013-12-12 17:30:41

标签: php mysql

我目前正在使用此代码根据创建日期在论坛中订购论坛帖子。

$e = mysqli_real_escape_string($_GET["forum"]);
$q = mysqli_query($con,
     "SELECT * FROM threads WHERE forum = '$e' ORDER BY date DESC LIMIT $offset,$rowsPerPage");

但是,这个顺序是创建日期的线程,而不是它们的活动 如何通过活动订购线程?

我正在考虑的事情 SELECT * FROM threads WHERE forum = '$e' ORDER BY (replies in this thread).date DESC LIMIT 5

这可能与否?

修改:
table thread holds the inital thread data
table replies holds the replies

2 个答案:

答案 0 :(得分:1)

添加一个列,其中包含最后一次将线程回复到threads表中的列,然后按此列使用订单。不要忘记更新新回复列。

有多种方法可以手动完成,但它比专用列慢得多。

答案 1 :(得分:0)

subselect-join将起到作用:

select t.* , lp.latestpost 
from threads as t 
inner join ( 
  select p.thread_id , max(p.date) as latestpost 
  from replies as p 
  group by p.thread_id
) as lp on pl.thread_id = t.id
order by lp.latestpost desc