On Wednesday, December 20, 2017 at 12:30:57 AM UTC-8, Hiren Mistry wrote:
>
> Hi
>
> I'm getting an unexpected result when using #last with #limit in queries. 
> The code setup is same from the sequel vs AR benchmark in my earlier post (
> code <https://github.com/hmistry/ar_sql/blob/master/sq/bench.rb>). 
>
> See code below:
> (byebug) Post.where(topic: topic).order(:updated_at).select_map(:id)
> [72, 61, 69, 13, 86, 35, 85, 7, 17, 29, 78, 12, 97, 68, 99, 52, 48, 56, 55
> , 26, 51, 89, 6, 33, 70, 16, 20, 9, 47, 38, 88, 63, 46, 65, 67, 5, 60, 44, 
> 18, 94, 74, 21, 100, 57, 83, 10, 96, 40, 64, 14, 23, 59, 73, 66, 34, 2, 84
> , 3, 11, 25, 80, 28, 98, 32, 1, 53, 90, 45, 19, 37, 75, 93, 27, 42, 76, 87
> , 36, 30, 43, 62, 4, 95, 82, 15, 31, 41, 91, 49, 79, 50, 58, 71, 39, 8, 24
> , 22, 81, 92, 77, 54]
>
> (byebug) Post.where(topic: 
> topic).order(:updated_at).offset(9).limit(1).select_map(:id)
> [29]
>
> (byebug) Post.where(topic: topic).order(:updated_at).offset(9).limit(1).
> select(:id).first
> #<Post @values={:id=>29}>
> # => I expect 29
>
> (byebug) Post.where(topic: topic).order(:updated_at).offset(9).limit(1).
> select(:id).last
> #<Post @values={:id=>58}>
> # => I expect 29
>
> (byebug) Post.where(topic: 
> topic).order(:updated_at).limit(10).select_map(:id)
> [72, 61, 69, 13, 86, 35, 85, 7, 17, 29]
>
> (byebug) Post.where(topic: topic).order(:updated_at).limit(10).select(:id
> ).first
> #<Post @values={:id=>72}>
> # => I expect 72
>
> (byebug) Post.where(topic: topic).order(:updated_at).limit(10).select(:id
> ).last
> #<Post @values={:id=>54}>
> # => I expect 29
>
>
> Is this correct? If so, then how is #last determining it's value?
>

Dataset#last is just reverse.first.  The limit you gave earlier is ignored, 
since last without an argument will set a limit of 1.

If you expect a subquery to be used automatically, that's not how it is 
implemented. You would need to do something like:

  Post.where(topic: 
topic).order(:updated_at).limit(10).from_self.order(:updated_at).select(:id).last

Or to get the last value in ruby:

  Post.where(topic: topic).order(:updated_at).limit(10).select(:id).all.last

You can also use the offset approach as you've shown above.

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to