Mysql限制每组的行数奇怪的结果
我想获取每个 symbolid
的最新 4 个日期。我改编了代码 此处如下:
set @num := 0, @symbolid := '';
select symbolid, date,
@num := if(@symbolid = symbolid, @num + 1, 1) as row_number,
@symbolid := symbolid as dummy
from projections
group by symbolid, date desc
having row_number < 5
并得到以下结果:
symbolid date row_number dummy
1 '2011-09-01 00:00:00' 1 1
1 '2011-08-31 00:00:00' 3 1
1 '2011-08-30 00:00:00' 5 1
2 '2011-09-01 00:00:00' 1 2
2 '2011-08-31 00:00:00' 3 2
2 '2011-08-30 00:00:00' 5 2
3 '2011-09-01 00:00:00' 1 3
3 '2011-08-31 00:00:00' 3 3
3 '2011-08-30 00:00:00' 5 3
4 '2011-09-01 00:00:00' 1 4
...
明显的问题是,为什么每个symbolid
我只得到3行,以及为什么它们被编号1,3,5?一些细节:
- 我尝试了强制索引和不强制索引(如此处所示),并且两种方式都得到了相同的结果。
- 日期是正确的,即列表正确显示了每个符号的前 3 个日期,但 row_number 值关闭
- 当我不使用“having”语句时,行号是正确的,即,最近的日期是 1,下一个最近的日期是 2,等等
显然,row_number
计算字段受到“having”子句的影响,但我不知道如何修复它。
我意识到我可以将“having”更改为“having row_number < 7”(6 与 5 相同),但它非常难看,并且想知道如何使其“行为”。
I wanted to get the latest 4 dates for each symbolid
. I adapted the code here as follows:
set @num := 0, @symbolid := '';
select symbolid, date,
@num := if(@symbolid = symbolid, @num + 1, 1) as row_number,
@symbolid := symbolid as dummy
from projections
group by symbolid, date desc
having row_number < 5
and get the following results:
symbolid date row_number dummy
1 '2011-09-01 00:00:00' 1 1
1 '2011-08-31 00:00:00' 3 1
1 '2011-08-30 00:00:00' 5 1
2 '2011-09-01 00:00:00' 1 2
2 '2011-08-31 00:00:00' 3 2
2 '2011-08-30 00:00:00' 5 2
3 '2011-09-01 00:00:00' 1 3
3 '2011-08-31 00:00:00' 3 3
3 '2011-08-30 00:00:00' 5 3
4 '2011-09-01 00:00:00' 1 4
...
The obvious question is, why did I only get 3 rows per symbolid
, and why are they numbered 1,3,5? A few details:
- I tried both forcing an index and not (as seen here), and got the same results both ways.
- The dates are correct, i.e., the listing correctly shows the top 3 dates per
symbolid
, but the row_number value is off - When I don't use the "having" statement, the row numbers are correct, i.e., the most recent date is 1, the next most recent is 2, etc
Obviously the row_number
computed field is being affected by the "having" clause, but I don't know how to fix it.
I realize that I could just change the "having" to "having row_number < 7" (6 gives the same as 5), but it's very ugly and would like to know what to do to make it "behave".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不是 100% 确定它为什么会这样(也许是因为逻辑上
SELECT
是在ORDER BY
之前处理的),但它应该按预期工作:I'm not 100% sure why it behaves this way (maybe it's because logically
SELECT
is processed prior toORDER BY
), but it should work as expected:用户定义的变量不能很好地工作,(请参阅此处)
这是我的建议
这种方法的缺点是它会将日期分组折叠,
并且需要先爆炸才能真正使用它。
The user defined variables does not work well, (refer here)
Here is my proposal
The drawback of this approach is it will group collapse the date,
and you need to explode before you can actually use it.
最终代码:
Final code: