php-mysql从数据库中获取下一个和上一个ID [英] php-mysql fetch next and previous id from a database

查看:312
本文介绍了php-mysql从数据库中获取下一个和上一个ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

**id**         **username**         **activity**
1              user1                  activity-like
2              user1                  activity-share
3              user3                  activity-like
4              user4                  activity-like
5              user1                  activity-share
6              user6                  activity-like
8              user1                  activity-share
9              user3                  activity-like
10             user5                  activity-share

(注意:没有id = 7)

(Note: there is no id = 7)

我正在尝试使用php-mysql来获取user1进行的活动并获取ID.在这种情况下,活动具有ID(1、2、5和8).

I am trying to use php-mysql to fetch the activity made by user1 and get the id. In this case the activities have the id (1, 2, 5, and 8).

$currentId = 5;

如果存在下一个和上一个ID,我想获取它们(在本例中为2和8).

I want to get the next and previous ids if they exist (in this case 2 and 8).

$fetch = mysql_query("SELECT * FROM `main` WHERE `username` = 'user1' AND id > '$id'");
if(mysql_num_rows($fetch) == 1){
while (){

}
$result = $fetch['id'];
}

我不确定该如何编写查询.

I am not sure how to write the query for that.

推荐答案

您可以执行以下操作:

对于下一个ID,

SELECT id from tablename where username = 'user1' AND id > $currentId ORDER BY ID ASC LIMIT 1;

对于以前的ID,

SELECT id from tablename where username = 'user1' AND id < $currentId ORDER BY ID DESC LIMIT 1;

这篇关于php-mysql从数据库中获取下一个和上一个ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆