I'm kind of stumped on this one. What I'd like to do is get all Orders that have the exact identical items and quantities to a given Order.
For example, Order number 100 has 1 Blue Widget, 2 Pink Widgets, and 1 Green Widget. I want to select all Orders from the database that also have exactly 1 Blue Widget, 2 Pink Widgets, and 1 Green Widget, and no items more or less than that.
The goal is to answer the question, "the last time this exact combination of items was shipped, what box did we ship it in?". If I can get orders that are an exact match in terms of items, I can see what box was used before.
My Table structure is:
Orders_Items
+---------------------------+-----------+-------------+
| OrderID | OrderPartID | ItemID | QtyOrdered |
+---------------------------+-----------+-------------+
| 1 | 21 | 4 | 11.5000 |
| 2 | 8 | 5 | 4.3333 |
+---------------------------+-----------+-------------+
Orders_OrderParts
+--------------+------------+-----------+
| OrderPartID | OrderID | StatusID |
+--------------+------------+-----------+
| 1 | 21 | 4 |
| 2 | 8 | 5 |
+---------------------------+-----------+
Orders_OrderParts_2_Shipments
+--------------+------------+--------------+
| OrderPartID | OrderID | ShipmentID |
+--------------+------------+--------------+
| 1 | 21 | 4 |
| 2 | 8 | 5 |
+---------------------------+--------------+
The "ShipmentID" is the magic number we're trying to find since it will tell me which boxes were used in the past.
I've started with this as a basis.
SELECT *, COUNT(*) AS ItemsInOrder
FROM Orders_Items OI
LEFT JOIN Orders_OrderParts OP
ON OP.OrderPartID = OI.OrderPartID
LEFT JOIN Orders_OrderParts_2_Shipments OP2S
ON OP2S.OrderPartID = OP.OrderPartID
WHERE OP.StatusID=800 # Only select Orders that have shipped.
GROUP BY OI.OrderPartID
This is a working query, but for now, it only returns all items grouped by order part. I need to remove all the order parts that don't contain the items in the current order part.
The Query:
SELECT * FROM `Orders_Items` WHERE OrderPartID = 100
returns all of the items in the current order part and their quantities, ie:
+--------------+------------+--------------+
| OrderPartID | ItemID | Quantity |
+--------------+------------+--------------+
| 100 | 21 | 1 |
| 100 | 8 | 3 |
+---------------------------+--------------+
So I need to narrow the first query by showing only order parts that have exactly 1 of Item #21, and exactly 3 of Item #8.
And that's where I'm stuck. I could do the two queries separately and use PHP to loop over the results and compare them, but I'm curious if it would be more efficient to use a pure MySQL solution... or if a single query is even possible in this situation?