我有一个具有以下结构的数据表:
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,我的结果将是行ID 3之前和行ID 2之后。
答案 0 :(得分: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
您可以将其中一个更改为&lt; =或&gt; =并添加WHERE id != ID
答案 1 :(得分: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等中可用。