php - 反转 mysql 资源

标签 php mysql resources reverse

//get the messages from the database
$messagesID_query = mysql_query("SELECT
                                   messageID,
                                   posterID,
                                   messageTime,
                                   message
                                 FROM
                                   chat_messages
                                 ORDER BY
                                   messageTime DESC
                                 LIMIT
                                   20");

上面的 mysql_query 从表中返回最新的 20 个条目。但是,理想情况下,我需要在获取行之前反转资源。

目前,我运行 2 个循环: 1 - 一个用于获取 php 数组中的所有结果 2 - 然后另一个处理数组以在反转后打印。

我正在尝试优化它的工作方式...是否可以在我开始获取行之前反转 mysql 资源,这样我就不必在 php 中反转数组?

或者,有没有一种方法我忽略了重写查询以按相反顺序返回所述行..但仍然像上面那样获得最新的 20 个结果?

最佳答案

这最好在查询中完成。将整个内容包装在一个子查询中,并按 messageTime 将其重新排序为升序。通过循环调用 mysql_data_seek() 以在比 20 更大的行集上向后获取行,这可以在数据库服务器上节省大量 CPU 资源。

SELECT * FROM 
(
  SELECT
    messageID,
    posterID,
    messageTime,
    message
  FROM
  chat_messages
  /* Subquery is used to get the most recent 20 by messageTime */
  ORDER BY messageTime DESC
  LIMIT 20
) subq
/* Reorder the result of the subquery to put them back into ascending order */
ORDER BY messageTime ASC

关于php - 反转 mysql 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194953/

相关文章:

mysql - 如何在mysql中获取行id

asp.net - .resx 文件更改时应用程序域重新启动。有什么办法可以避免这种情况?

python - 导入错误: No module named 'resource' on windows

php - 使用 imagecopyresampled 调整大小时图像颜色被破坏

php - AuthenticationFailedServer 无法对 azure 中的请求进行身份验证

php - 在 Doctrine 2 的映射关系中保留选定的实体

mysql - 减去日期MySQL中的秒数

php - 在 codeigniter 中用于分页的自定义 css

php - 使用 Hostgator 连接到 MySql 数据库

c# - 您将如何在 C# 项目中存储表格常量数据?