我有一个 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/