I need some help with a view.
I have 2 tables that I need to "merge" together.
First table contains info about products (product-color-size), and the other tables has info about stock, sold, avilable (quantity) etc on product-season-color-size niveau.
I need my view to return available pr product. The same product-color-size can be multiple times (It can be on multiple seasons), and therefore I can't just sum on ex available.
My query looks like this
SELECT
SUM((
SELECT
SUM(products_details.available)
FROM
products_details
WHERE
products_details.product_id = products.id
)) AS available
FROM
products
But, this will not work. If one size has 6 in available and another has -5, the query will return 1 available. But, I actually got 6, I can sell.
Therefore I need to do some adjustments
SELECT
SUM((
SELECT
SUM(
IF(
products_details.available > 0,
products_details.available,
0
)
)
FROM
products_details
WHERE
products_details.product_id = products.id
)) AS available
FROM
products
But, this will also not work. If the size has 6 in available on one season, and -5 on another, the query will return 6 available. But, these two rows I need to sum, because it's the same product. Therefore it needs to return 1 available.
So, I came up with
SELECT
SUM(
IF(
(
SELECT
SUM(
IF(
products_details.available > 0,
products_details.available,
0
)
)
FROM
products_details
WHERE
products_details.product_id = products.id
) > 0,
(
SELECT
SUM(
IF(
products_details.available > 0,
products_details.available,
0
)
)
FROM
products_details
WHERE
products_details.product_id = products.id
),
0
)
) AS available
FROM
products
But, that will be very (!!) slow. Can I somehow use the same subquery multiple times? So I can use it in the If-statement, and if it's positive I can use the same value to use in the sum?
It's pretty complex, but I hope someone can help me
/Mads
Edit
I just found out, that I can write
SELECT
SUM((
SELECT
IF(
SUM(products_details.available) > 0,
SUM(products_details.available),
0
)
FROM
products_details
WHERE
products_details.product_id = products.id
)) AS available
FROM
products
That could work okay
Edit2
I found a new and much quicker way to write it, and it works just fine :-)
SELECT
SUM(GREATEST(0,(
SELECT
SUM(products_details.available)
FROM
products_details
WHERE
products_details.product_id = products.id
))) AS available
FROM
products
GROUP BY
products.id
This is very quick - from about 10 sec to just above 1 sec.