SQL - 在给定特定 WHERE 子句的情况下查找下一行和上一行

标签 sql mysql

我有一个 bbPress 论坛使用的名为 bb_posts 的 MySQL 表。它有一个名为 topid_id 的自增字段和另一个名为 topic_poster 的字段。

我正在尝试编写一个函数来查找“同一作者的下一篇文章”。因此,例如,假设用户在显示主题 123 的特定页面上。如果您执行 SQL 查询:

SELECT *
FROM `bb_topics`
WHERE `topic_poster` = 5
ORDER BY `topic_id` ASC

这可能会返回以下行:

topic_id    topic_poster
6           5
50          5
123         5
199         5
2039        5

我想做的是编写一个返回这两行的 SQL 查询:

topic_id    topic_poster
50          5
199         5

这将是 topic_id 为 123 的行之前的行,以及该行之后的行。

如果在一个查询中很难做到这一点,那么将其分成两个查询绝对没问题...

我想避免执行整个 SQL 查询(“SELECT * FROM bb_topics WHERE topic_poster = 5”)并循环遍历结果,因为结果集有时很大。

这可能吗? :-)

最佳答案

下一个:

SELECT * FROM `bb_topics` 
      WHERE `topic_id` = 
      (select min(`topic_id`) FROM `bb_topics` where `topic_id` > 123
         and `topic_poster` = 5)

上一个:

SELECT * FROM `bb_topics` 
      WHERE `topic_id` = 
      (select max(`topic_id`) FROM `bb_topics` where `topic_id` < 123
         and `topic_poster` = 5)

两者:

SELECT * FROM `bb_topics` 
      WHERE `topic_id` = 
      (select min(`topic_id`) FROM `bb_topics` where `topic_id` > 123
                     and `topic_poster` = 5)
      or `topic_id` = 
      (select max(`topic_id`) FROM `bb_topics` where `topic_id` < 123
                        and `topic_poster` = 5)

关于SQL - 在给定特定 WHERE 子句的情况下查找下一行和上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/645102/

相关文章:

sql - 选择 SQL 列作为添加的行

php - 我如何在 cakePHP 中编写带有右连接的子查询?

mysql - 为 liquibase 中的插入查询定义变更集

php - WordPress 显示按自定义分类过滤的 CPT

php - 无法弄清楚为什么 header 位置不适用于这种情况(php)

c# - 将其转换为 SQL 的最佳方法是什么

mysql - 从数据库中获取所有订单 - 只返回一行

sql - 如何删除 oracle 中破折号后的文本?

java - JPA criteriabuilder where 语句

mysql - linux下mysql从哪个目录启动