4

我有一个具有以下结构的数据表:

id |   likes
1  |     2
2  |     5
3  |     2
4  |     6
5  |     2

如果想找到 #3 旁边的行,我可以使用:

SELECT * FROM table WHERE id >= 3 ORDER BY id

但是我想做的是按表按赞排序。当数据按喜欢排序时,它看起来像这样

id |   likes
1  |     2
3  |     2
5  |     2
2  |     5
4  |     6

当按喜欢排序时,如何选择某个 id 之前或之后的行?例如对于 id 5,我的结果将是 row id 3 之前和 row id 2 之后。

4

2 回答 2

1

如果喜欢是唯一的数字,则以下应该有效。

以前的:

SELECT * FROM table WHERE likes < (SELECT likes FROM table WHERE id = ID) ORDER BY likes DESC LIMIT 1

下一个:

SELECT * FROM table WHERE likes > (SELECT likes FROM table WHERE id = ID) ORDER BY likes ASC LIMIT 1

您可以将其中 1 个更改为 <= 或 >= 并添加WHERE id != ID

于 2013-07-17T11:07:36.787 回答
0

顺便说一句,您的第二个表显示前两行的错误 ID。

它应该是:

id    likes

 1    2 

 3    2

这适用于我的MySQL:

Select id, likes from (SELECT id, @rownum:=@rownum+1 AS rownum, likes
FROM table u, (SELECT @rownum:=0) r ORDER BY likes) as derived  where
rownum >= 2 and rownum <= 4;

(SELECT id, @rownum:=@rownum+1 AS rownum, likes FROM table u, (SELECT
@rownum:=0) r ORDER BY likes);

最后一部分尝试模拟行号,这在 MySQL 中是缺失的,但在 MSSQL、Oracle 等中可用。

于 2013-07-17T11:16:06.323 回答