0

大家好,像往常一样,感谢任何花时间阅读本文的人。

我正在尝试显示与已提出的问题相关的所有答案。我正在使用 Kohana 3。

到目前为止,我可以通过以下方式确定哪条记录的 vote_points 最高:

$best_id = DB::query(Database::SELECT, 'SELECT id FROM answers WHERE vote_points=(SELECT MAX(vote_points) FROM answers) AND question_id ='.$question->id)->execute();

而且,我收集了所有答案并通过将结果集放在 foreach 循环中来显示它们:

<?php foreach($question->answers->where('moderated', '=', 0)->where('deleted', '=', 0)->order_by('created_at', 'ASC')->find_all() as $answer): ?> 
A bunch of display answer functions and divs~~~

我需要找到一种方法来确保首先显示带有 $best_id 的记录,并且只显示一次,而其余的答案由 created_at asc 显示和排序。

谢谢大家!

4

2 回答 2

1

这个查询应该做必要的:

select * 
from answers where question_id = X
order by 
  (points = (select max(points) from answers where question_id = X)) desc,    
  created_at asc
于 2010-08-16T18:25:19.847 回答
0

我会这样写:

SELECT id, count(id) as C FROM answers group by id order by C desc limit 10 

(仅当您需要特定数字时才限制 10 个)

然后您可以遍历结果,将每个结果填充到一个数组中:

$all = array ();
while ( $rs = mysql_fetch_array ( $r, MYSQL_ASSOC ) )
{
    $all[$rs['id']] = $rs['C'];
}

$best = array_shift($all);

// echo the best one here

// loop over the rest

foreach ( $all as $id => $count )
{
    // display code here
}
于 2010-08-16T18:15:10.097 回答