Skip to content

Instantly share code, notes, and snippets.

@gamov
Last active June 7, 2016 10:02
Show Gist options
  • Save gamov/184249a3328bcfa333ae3fc7ba3ad9de to your computer and use it in GitHub Desktop.
Save gamov/184249a3328bcfa333ae3fc7ba3ad9de to your computer and use it in GitHub Desktop.
ActiveRecord Auto Aliasing
-- shipments is aliased to shipments_shipping_items by AR because it is present in the subquery
-- this particular query fails because we join business_sites on shipments but shipments was aliased shipments_shipping_items
SELECT
`shipping_items`.*
FROM
`shipping_items`
INNER JOIN
`item_variants` ON `item_variants`.`id` = `shipping_items`.`item_variant_id`
INNER JOIN
`shipments` `shipments_shipping_items` ON `shipments_shipping_items`.`id` = `shipping_items`.`shipment_id`
INNER JOIN
`shipment_bookings` `shipment_bookings_shipments_2` ON `shipment_bookings_shipments_2`.`id` = `shipments_shipping_items`.`shipment_booking_id`
LEFT OUTER JOIN
`item_families` ON `item_families`.`id` = `item_variants`.`item_family_id`
LEFT OUTER JOIN
`business_sites` ON `business_sites`.`id` = `shipments`.`dest_site_id`
INNER JOIN
-- subquery starts here
(SELECT
shipments.dest_site_id,
MAX(shipment_bookings.eta) AS max_eta,
shipping_items.item_variant_id
FROM
`shipping_items`
INNER JOIN `shipments` ON `shipments`.`id` = `shipping_items`.`shipment_id`
INNER JOIN `shipment_bookings` ON `shipment_bookings`.`id` = `shipments`.`shipment_booking_id`
LEFT OUTER JOIN `shipment_bookings` `shipment_bookings_shipments` ON `shipment_bookings_shipments`.`id` = `shipments`.`shipment_booking_id`
WHERE
`shipments`.`workflow_state` IN ('shipping' , 'unloading', 'completed', 'wrapping')
AND ((shipments.processing_flags & 128 = 128))
AND (`shipments`.`dest_site_id` != 1
OR `shipments`.`dest_site_id` IS NULL)
AND (`shipment_bookings`.`eta` > '2015-10-07')
AND (`shipments`.`dest_site_id` IS NOT NULL)
GROUP BY shipments.dest_site_id , `shipping_items`.`item_variant_id`) AS sub ON sub.dest_site_id = shipments_shipping_items.dest_site_id
AND shipment_bookings_shipments_2.eta = sub.max_eta
AND shipping_items.item_variant_id = sub.item_variant_id
-- subquery ends
WHERE
`item_variants`.`item_family_id` = 41
AND `business_sites`.`selling_place_id` = 30
ORDER BY shipments_shipping_items.dest_site_id , `item_families`.`category_id` ASC , `item_families`.`brand` ASC , `item_families`.`name` ASC , `item_variants`.`variant_group_id` ASC , `item_variants`.`first_name` ASC , `item_variants`.`packaging` ASC
@shipping_items = accessible(ShippingItem).joins(shipment: :shipment_booking).
joins(" INNER JOIN (#{subquery.to_sql}) AS sub ON sub.dest_site_id = shipments_shipping_items.dest_site_id AND shipment_bookings_shipments_2.eta = sub.max_eta AND shipping_items.item_variant_id = sub.item_variant_id")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment