Skip to content

Instantly share code, notes, and snippets.

@caseydentinger
Last active December 12, 2015 12:39
Show Gist options
  • Save caseydentinger/4773248 to your computer and use it in GitHub Desktop.
Save caseydentinger/4773248 to your computer and use it in GitHub Desktop.
select sql_no_cache o.*
from (select * from orders where orders_status = 1) o
where (
select count(*) from orders_products op
join products p on op.products_id = p.products_id
join parts pa on p.products_id = pa.products_id
where op.products_quantity > (
p.products_physical_quantity - ifnull(
(
select sum(rs.quantity)
from (select * from orders where orders_status in (1, 5)) o
join reserved_stock rs on o.orders_id = rs.order_id
where rs.part_id = pa.parts_id
), 0)
)
and op.orders_id = o.orders_id
) = 0
@randykarels
Copy link

this is slower, but I think more readable and extensible. Hope this helps.

select sql_no_cache
  orders.*

FROM ( # the subset of new orders

  SELECT orders_id, date_purchased, orders_status FROM orders 
  WHERE orders_status = 1 # other constraints on orders can go here
  GROUP BY orders_id

) AS orders

INNER JOIN orders_products AS op ON orders.orders_id = op.orders_id

INNER JOIN ( # products with their reserve stock amounts

  SELECT DISTINCT parts.products_id, IFNULL(reserved_qty, 0) as reserved_qty
  FROM parts
  LEFT JOIN (

        # total reserved stock by part
        select part_id, sum(rs.quantity) as reserved_qty
        FROM reserved_stock AS rs
        WHERE rs.order_id in (

          #all orders contributing to reserved stock
          select distinct orders_id 
          from orders 
          where orders_status in (1, 5)

        ) 
        group by part_id

  ) as reserved ON parts.parts_id = reserved.part_id

) as parts ON op.products_id = parts.products_id

WHERE op.products_quantity>parts.reserved_qty
GROUP BY orders_id

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment