-
Notifications
You must be signed in to change notification settings - Fork 869
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sending extra SQL queries when model uses joins, includes #423
Comments
I'm having a similar problem (on Rails 4.1.x), but it seems like a Rails issue with eager load combined with limit/offset. If you do:
You might still get the extra queries. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm trying to get adverts with attachments(advert has_many attachments). If I use query without pagination:
@adverts = Advert.where(category_id: params[:id]).includes(:attachments).references(:attachments)
I get result in single query.
SELECT
adverts
.id
AS t0_r0,adverts
.created_at
AS t0_r1,adverts
.updated_at
AS t0_r2,adverts
.category_id
AS t0_r3,adverts
.title
AS t0_r4,adverts
.body
AS t0_r5,adverts
.user_id
AS t0_r6,adverts
.visible
AS t0_r7,adverts
.attachments_count
AS t0_r8,attachments
.id
AS t1_r0,attachments
.image
AS t1_r1,attachments
.created_at
AS t1_r2,attachments
.updated_at
AS t1_r3,attachments
.advert_id
AS t1_r4 FROMadverts
LEFT OUTER JOINattachments
ONattachments
.advert_id
=adverts
.id
WHEREadverts
.category_id
= 1It supposes if I use pagination - the result will be in two queries(one is adverts with attachments, second count of adverts). But I get three queries: with limit, with attachments, and count.
@adverts = Advert.where(category_id: params[:id]).includes(:attachments).references(:attachments).page(params[:page])
SELECT DISTINCT
adverts
.id
FROMadverts
LEFT OUTER JOINattachments
ONattachments
.advert_id
=adverts
.id
WHEREadverts
.category_id
= 1 LIMIT 10 OFFSET 0SELECT
adverts
.id
AS t0_r0,adverts
.created_at
AS t0_r1,adverts
.updated_at
AS t0_r2,adverts
.category_id
AS t0_r3,adverts
.title
AS t0_r4,adverts
.body
AS t0_r5,adverts
.user_id
AS t0_r6,adverts
.visible
AS t0_r7,adverts
.attachments_count
AS t0_r8,attachments
.id
AS t1_r0,attachments
.image
AS t1_r1,attachments
.created_at
AS t1_r2,attachments
.updated_at
AS t1_r3,attachments
.advert_id
AS t1_r4 FROMadverts
LEFT OUTER JOINattachments
ONattachments
.advert_id
=adverts
.id
WHEREadverts
.category_id
= 1 ANDadverts
.id
IN (130, 131, 132, 136, 144, 150, 151, 153, 155, 158)SELECT COUNT(DISTINCT
adverts
.id
) FROMadverts
LEFT OUTER JOINattachments
ONattachments
.advert_id
=adverts
.id
WHEREadverts
.category_id
= 1Is it possible to get rid of extra query?
The text was updated successfully, but these errors were encountered: