PHP - 如何一起使用ORDER BY和GROUP BY

时间:2013-07-01 00:13:12

标签: php mysql database group-by

我创建了一个包含message, sender, to, time的表格我希望按发件人分组并按时间顺序这是我的代码

$query= mysql_query("SELECT * FROM  `table` ORDER BY `time` GROUP BY `sender`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr ['message'];
echo '</br>';
echo $msg;
}

显示此错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY发送方' at line 1

那么如何解决这个问题?

谢谢你 克劳斯

3 个答案:

答案 0 :(得分:2)

请注意您的优先顺序。结果分组后,应该订购。

"SELECT * FROM  `table`  GROUP BY `sender` ORDER BY `time`"

答案 1 :(得分:1)

试试这段代码

 $query= mysql_query("SELECT * FROM  `table`  GROUP BY `sender` ORDER BY `time` ")or  die(mysql_error());
                                             // ^^--will be before order                    
    $num = mysql_num_rows($query);  // out of the while loop
    while($arr = mysql_fetch_array($query)){
    $msg = $arr['message'].'<br />';
           // ^^--remove space here
    echo $msg;
    }

答案 2 :(得分:0)

如何使用自联接来获得每组的max / min / something-n行。

在您的情况下,它可以应用于您想要的效果:

SELECT * FROM
(SELECT group_id, MAX(`yourdate`) AS yourdate FROM tbl_name GROUP BY group_id)
AS x JOIN tbl_name USING (`group_id`,yourdate);