duanmei1930 2014-05-29 19:33
浏览 10
已采纳

最受评论和最少评论的mySQL排序

I'm trying to order a list of items based on the amount of comments for each topic as shown below:

$page = $_GET['page'];

$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");

if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];

//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}

What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber

  • 写回答

2条回答 默认 最新

  • dongshipang8094 2014-05-29 19:38
    关注

    The first query should be:

    SELECT t.*, COUNT(c.topic_id) AS count
    FROM topic AS t
    LEFT JOIN comments AS c ON c.topic_id = t.topic_id
    WHERE t.cat_id = '$page'
    GROUP BY t.topic_id
    ORDER BY count
    LIMIT $start, $per_page
    

    You can get $commentnumber with:

    $commentnumber = $rows['count'];
    

    You don't need the second query at all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100