So, I have two tables, customers
and orders
and I want to get all orders associated with a customer.
The tables look like this:
Customers
customer_no order_no
1027 V327
1027 V391
1028 V400
etc..
Orders
order_no article1 article2 size order_date quantity
V327 Jeans Black 36 20150101 2
V327 Shirt Blue L 20150101 1
V327 Shirt White L 20150101 2
V391 Jeans Red 34 20150202 3
V400 Shirt Green 32 20150226 2
etc..
Now, I currently use the following query, but it is dog slow and I just know I'm approaching this wrongly. I feel like it should be possible to solve this with a join somewhere, but for the life of mine, I just cannot figure this one out.
SELECT article1, article2, size, order_date, SUM(quantity)
FROM orders
WHERE order_no IN (
SELECT order_no
FROM customers
WHERE customer_no = '1027'
)
GROUP BY article1, article2, size, order_date, SUM(quantity)
The output for customer 1027 is (and should be):
article1 article2 size order_date SUM(quantity)
Jeans Black 36 20150101 2
Shirt Blue L 20150101 1
Shirt White L 20150101 2
Jeans Red 34 20150202 3
Does anyone have a better way of solving this? Performance is my main issue here.
order_no
appears in thecustomers
table. \$\endgroup\$GROUP BY
an aggregate function (SUM(quantity)
) looks extremely wrong to my eye. \$\endgroup\$size
rather thanSUM(quantity)
. I have no idea what brainfart of mine caused me to write that in theGROUP BY
statement. \$\endgroup\$size
in the list, though. If it's not supposed to be there, then it looks to me like you just copied your output column list and forgot to delete it off the end. No harm. Just glad we got it cleared up. \$\endgroup\$