Skip to content
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

[Question] Join a subquery #66

Open
shlajin opened this issue May 7, 2017 · 3 comments
Open

[Question] Join a subquery #66

shlajin opened this issue May 7, 2017 · 3 comments

Comments

@shlajin
Copy link

shlajin commented May 7, 2017

First of all, that's an awesome gem and I'm super happy I found it 🔥 🔥 🔥

The "parent" gem (squeel) has an ability of joining a subquery, example from their readme:

subquery = OrderItem.group(:orderable_id).select { [orderable_id, sum(quantity * unit_price).as(amount)] }
Seat.joins { [payment.outer, subquery.as('seat_order_items').on { id == seat_order_items.orderable_id}.outer] }.
              select { [seat_order_items.amount, "seats.*"] }
# => SELECT "seat_order_items"."amount", seats.*
#    FROM "seats"
#    LEFT OUTER JOIN "payments" ON "payments"."id" = "seats"."payment_id"
#    LEFT OUTER JOIN (
#      SELECT "order_items"."orderable_id",
#             sum("order_items"."quantity" * "order_items"."unit_price") AS amount
#      FROM "order_items"
#      GROUP BY "order_items"."orderable_id"
#    ) seat_order_items ON "seats"."id" = "seat_order_items"."orderable_id"

I wonder if there's an ability to achieve the same thing with baby squeel?

@Looooong
Copy link

Looooong commented May 9, 2017

I believe this can be worked out without subquery:

# You don't seem to use `payment` so I ommit it
Seat.joining { order_items.outer }.grouping { [id, order_items.orderable_id] }
.selecting { [sum(order_items.quantity * order_items.unit_price).as('amount'), 'seats.*'] }

This requires OrderItem to be Seat's association - either with polymorphic behaviour or with explicit foreign key.

@shlajin
Copy link
Author

shlajin commented May 19, 2017

Provided example is taken from the squeel readme for illustration purposes. I can't deny that many SQL queries can be transformed from subquery based to non-subquery based, but in many cases subquery is just easier to write. Would be awesome to have that ability / choice :)

@rzane
Copy link
Owner

rzane commented May 19, 2017

Yeah, I agree that it would be nice for baby squeel to provide this functionality, but I'm having trouble finding the time to add new features. I'd be thrilled to receive a pull request!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants