0

我创建了一个表,其中包含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

那么如何解决这个问题呢?

谢谢克劳斯
_

4

3 回答 3

2

注意你的优先级。结果分组后,应进行排序。

"SELECT * FROM  `table`  GROUP BY `sender` ORDER BY `time`"
于 2013-07-01T00:15:11.043 回答
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;
    }
于 2013-07-01T00:23:43.723 回答
0

如何使用自联接来获得每组的最大/最小/某事-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);
于 2016-09-09T11:29:39.150 回答