这是一个包含 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);
我可以像这样添加行号列( fiddle :http://sqlfiddle.com/#!2/dade4/3):
select id, @r:=@r+1 r
from test a
join (select @r:=0) b;
然后我尝试使用 HAVING
子句获取前 10 个项目( fiddle :http://sqlfiddle.com/#!2/dade4/4):
select id, @r:=@r+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 之间的行?
(我没有使用 LIMIT,因为在不同的查询中,我需要为每个类别选择前 n 个项目)
最佳答案
我同意其他答案,having
不是办法,但如果您需要使用它,那么:
select id, @r:=@r+1 r
from test a
join (select @r:=0) b
having @r+1 <= 10;
这里是 demo in SQLFiddle .
你得到错误结果的原因是因为 MySql 计算了两次别名 r(在 select 和 having 中),所以 @r:=@r+1
被执行了两次。
关于mysql - 选择具有特定行号值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24173256/