Mysql查询最近一行的连接表

时间:2016-04-22 01:21:31

标签: php mysql

我有一个类别的页面,他们工作正常,直到我加入。

类别显示如下:

  

类别1 ----------------------- 0 ---------- 0
  讨论1由某人

     

类别2 ----------------------- 0 ---------- 0
  讨论2由personelse

现在讨论的内容,我需要根据discussion_id显示发布到该类别的最后一次讨论。我已经尝试了ORDER BY ... DESC,但它按类别名称排序,而不是讨论名称和发布者。

 $sql = "SELECT *, COUNT(d.cat_id) as count 
         FROM discussions as d 
         LEFT JOIN categories c ON (c.cat_id = d.cat_id) 
         RIGHT JOIN soldiers s ON (s.uid = d.discussion_poster) 
         GROUP BY d.cat_id";
 $result = query($sql);  


while (($row = mysqli_fetch_assoc($result)) != false) {       
   $cat_id = $row['cat_id']; 
   $discussion_id = $row['discussion_id'];
   $cat_title = $row['cat_title'];
   $discussion_title = $row['discussion_title']; 
   $discussion_time = $row['discussion_time'];
   $count = $row['count'];
   $discussion_poster_id = $row['discussion_poster'];
   $discussion_poster = $row['soldier'];
}

1 个答案:

答案 0 :(得分:0)

$sql = "
SELECT *
FROM categories c
INNER JOIN
(
   SELECT MAX(discussion_id) discussion_id,
   COUNT(discussion_id) as count,
   cat_id
   FROM
   discussions
   GROUP BY
   cat_id
) as d1
ON (c.cat_id = d1.cat_id)
INNER JOIN discussions as d
ON (d1.discussion_id = d.discussion_id)
INNER JOIN soldiers s
ON (s.uid = d.discussion_poster)
GROUP BY d.cat_id";