繁体   English   中英

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

[英]PHP - How to Use ORDER BY and GROUP BY together

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

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

谢谢
克劳斯

注意您的优先级。 将结果分组后,应将其排序。

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

试试这个代码

 $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;
    }

如何使用自连接来获取每个组的最大/最小/某物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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM