下面是一个包含20个项目的测试表。选择具有特定行号值的行
create table test (id int not null primary key);
insert into test values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18),(19);
我可以这样添加行号列(提琴:http://sqlfiddle.com/#!2/dade4/3):
select id, @r:[email protected]+1 r
from test a
join (select @r:=0) b;
然后我试图让第一10个项目有HAVING
条款(小提琴:http://sqlfiddle.com/#!2/dade4/4):
select id, @r:[email protected]+1 r
from test a
join (select @r:=0) b
having r <= 10;
这里有意想不到的结果:
ID| R
------
0 | 2
1 | 4
2 | 6
3 | 8
4 | 10
这是为什么,以及如何检索r在1和10之间的行?
(我没有使用限制,因为在不同的查询,我需要选择每个类别的前n项)