我有下表:
**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)
我正在尝试使用php-mysql来获取user1所做的活动并获取id。在这种情况下,活动具有id(1,2,5和8)。
$currentId = 5;
我想获得下一个和之前的ID(如果它们存在的话(在本例中为2和8)。
$fetch = mysql_query("SELECT * FROM `main` WHERE `username` = 'user1' AND id > '$id'");
if(mysql_num_rows($fetch) == 1){
while (){
}
$result = $fetch['id'];
}
我不知道如何为此编写查询。
答案 0 :(得分:5)
您可以这样做:
对于下一个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;
答案 1 :(得分:1)
我认为您可以使用union
查询,如下所示:
(SELECT ID, USERNAME, ACTIVITY FROM MAIN WHERE username = 'user1' AND ID < '$id'
ORDER BY ID DESC LIMIT 1)
UNION
(SELECT ID, USERNAME, ACTIVITY FROM MAIN WHERE username = 'user1' AND ID > '$id'
ORDER BY ID ASC LIMIT 1);
第一个查询片段应返回ID = 2
(如果存在),第二个应返回ID = 8
。