views:

34

answers:

2

Hello everyone and as usual, thank you to anyone taking the time to read this.

I am attempting to display all of the answers relevant to a question that has been asked. I am using Kohana 3.

So far, I am able to determine which record has the highest amount of vote_points via:

$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();

And, I gather all of my answers and display them by placing the result set in a foreach loop:

<?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~~~

I need to figure out a way to ensure that the record with $best_id is displayed first, and only once, while the rest of the answers are displayed and ordered by created_at asc.

Thank you, everyone!

A: 

I would write that something like:

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

(limit 10 only if you want a specific number)

Then you can loop over the result, stuff each into an array:

$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
}
Hans
A: 

This query should do the needful:

select * 
from answers where question_id = X
order by 
  (points = (select max(points) from answers where question_id = X)) desc,    
  created_at asc
ovais.tariq