php - 当日期相同时从 MySQL 获取下一个和上一个

标签 php mysql

现在我遇到了一个问题,因为从外部源将行导入数据库的速度太快了。

如果创建的多行具有完全相同的发布日期,则无法按日期排序并按顺序滚动浏览帖子。

假设 5 行都是在上午 11:22:04 准确生成的:

  • 第 1 行 - 上午 11:22:04
  • 第 2 行 - 上午 11:22:04
  • 第 3 行 - 上午 11:22:04
  • 第 4 行 - 上午 11:22:04
  • 第 5 行 - 上午 11:22:04

如果访问者正在查看第 3 行并想要“下一行”,我将要求数据库为我提供晚于或等于上午 11:22:04 发布的下一行,即第 1 行无论我做什么。

  • 如果我不说“或等于”,那就意味着访问者永远不会看到第 4 行或第 5 行,这与总是看到第 1 行一样糟糕。
  • 将行 ID 添加到 order by 子句并没有什么帮助,因为它总是会给出第 1 行(如果我当前正在查看第 3 行)。
  • where 子句中添加大于或小于没有任何帮助,因为 - 例如 - 如果我正在查看第 3 行并且我想要“下一个”行,但说ID 必须大于 3,否则我永远不会得到第 1 行。

我可以通过更新数据库中在同一时间发布的每一行(以行 ID 作为秒)来欺骗系统,这会将上述记录变成:

  • 第 1 行 - 上午 11:22:01
  • 第 2 行 - 上午 11:22:02
  • 第 3 行 - 上午 11:22:03
  • 第 4 行 - 上午 11:22:04
  • 第 5 行 - 上午 11:22:05

这实际上非常有效。问题是每次管理员导入数据时都会添加新行,而我无法不断更新数据库来纠正此问题。

我获取下一个和上一个的查询如下所示:

// next row
select  t.*
from    table t
where   t.postdate  >= '{$current_date}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate
limit   1

// previous row
select  t.*
from    table t
where   t.postdate  <= '{$current_date}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate desc
limit   1

(是的,我已经在 google 上广泛搜索了这个问题,并在 Stackoverflow 上查看了几个类似的问题!)

最佳答案

你能尝试这样的事情吗:

// next row
select  t.*
from    table t
where   CONCAT(t.postdate, t.id)  >= '{$current_date}{$current_id}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate
limit   1

// previous row
select  t.*
from    table t
where   CONCAT(t.postdate, t.id)  <= '{$current_date}{$current_id}'
and     t.postdate  < now()
and     t.id        <> {$current_id}
order   by t.postdate desc
limit   1

关于php - 当日期相同时从 MySQL 获取下一个和上一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31956196/

相关文章:

php - 在没有 php.ini 的情况下设置 display_errors=0 和 log_errors=1

php - 了解 fatal error : Cannot use temporary expression in write context

javascript - 使用ajax调用prestashop中的 Controller

python - matplotlib mySQL 空白图

php - 选择随机数据库行 WHERE ID=由 PHP 函数创建的随机值

php - 从多个表加载详细信息

php - 单击按钮运行 PHP 代码

php - Paypal IPN - 在数据库中存储数据,更新和删除

mysql - 过去 7 天内至少登录一次的用户数量(逐日)

mysql - mysql中选择查询的问题