如何将PHP排序替换为SQL


How to replace the PHP sorting to SQL?

伪码

$res = Query("SELECT * FROM `table` ORDER BY `date` DESC LIMIT 15");
SortArray(&$res, 'date', 'asc');

如果用单词描述,那么取最后一部分数据是按降序从数据库中排序的,但要给出按升序排序的数据。

尝试:

$res = Query("SELECT * FROM ( SELECT * FROM `table` ORDER BY `date` DESC LIMIT 15) ORDER BY `date` ASC");

您可以使用usort函数按特定键对数组进行排序:

$res_array=array();  
while($row=mysql_fetch_row($res))  
   $res_array[]=$row;  
$new_arr = usort($res_array,"my_func");  
function my_func($a, $b)  
{  
    if ($a['date'] == $b['date']) {  
        return 0;  
    }  
    return ($a['date'] < $b['date']) ? -1 : 1;  
}   

*可能需要进行一些调试。接受这个想法。

与其进行一些神奇的SQL查询,不如按降序选择前15行。然后只需阅读最后的结果。

$statement = $pdo->query('SELECT * FROM `table` ORDER BY `date` DESC LIMIT 15');
if ( ! $statement->execute())
{
    throw new Exception('query failed !');
}
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
while ( $row = array_pop($data))
{
    var_dump( $row );
}