[英]MySQL: How do I select the next or previous row from database?
I've got a table called " posts
", and within that table a column with " post_id
" (A long with other columns ofc). 我有一个名为“ posts
”的表,该表中有一post_id
“ post_id
”(与c的其他列很长)。
How to I select the next (or previous) row from the table, by " post_id
"? 如何通过“ post_id
”从表中选择下一行(或上一行)?
Let's say my current " post_id
" is 15. Now I need to select the next row, where certain conditions are met, so I need to put in some where clauses. 假设我当前的“ post_id
”为15。现在,我需要选择满足某些条件的下一行,因此需要放入一些where子句。
I'm bad at explaining this I feel. 我很无法解释我的感受。 I'm looking for something like this: 我正在寻找这样的东西:
SELECT (next row) FROM posts WHERE post_draft=0 && post_approved=1
Can anybody help me with this? 有人可以帮我吗?
Relational database system have no concept of a "next row" or "previous row". 关系数据库系统没有“下一行”或“上一行”的概念。 That is because there is no natural order of entries in such a database. 那是因为在这样的数据库中没有自然的条目顺序。 So there terms "next" and "previous" are not really defined. 因此,“下一个”和“上一个”这两个术语并未真正定义。
You can however implement a query that delivers what you are looking for: 但是,您可以实现一个查询,该查询可以提供您要查找的内容:
SELECT *
FROM posts
WHERE post_id>15
AND post_draft=0
AND post_approved=1
ORDER BY post_id ASC
LIMIT 1;
So if you have the current post_id
it is easy to pick the "next" entry according to a given order of a result set. 因此,如果您具有当前的 post_id
,则可以根据给定的结果集顺序轻松选择“下一个”条目。 The same is obviously possible for the "previous" entry. 对于“上一个”条目显然也可以这样做。
I would use something like this. 我会用这样的东西。
$next_post_query = "SELECT * FROM `posts` WHERE `post_draft`=0 AND `post_approved`=1 AND `post_id` > {$current_post_id} order by `post_id` asc limit 1";
$prev_post_query = "SELECT * FROM `posts` WHERE `post_draft`=0 AND `post_approved`=1 AND `post_id` < {$current_post_id} order by `post_id` desc limit 1";
假设post_id列是自动递增的,则可以尝试
select * from posts where post_id in (select post_id+1 from posts where post_draft=0 and post_approved=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.