i made a query for sql but it’s really heavy and i really don’t see how i can optimize it, the explanations comes after :
SELECT tyds.user_tyd,
tyds.product_tyd,
tyds.action_tyd,
products.price_product,
data_8,
data_9,
avg_8,
sum_9
FROM tyds
INNER JOIN products
ON tyds.product_tyd = products.id_product
INNER JOIN (SELECT product_tyd,
Avg(data_tyd) AS avg_8
FROM tyds
WHERE action_tyd = 8
GROUP BY product_tyd) Agg_1
ON Agg_1.product_tyd = tyds.product_tyd
INNER JOIN (SELECT product_tyd,
Sum(data_tyd) AS sum_9
FROM tyds
WHERE action_tyd = 9
GROUP BY product_tyd) Agg_2
ON Agg_2.product_tyd = tyds.product_tyd
INNER JOIN (SELECT product_tyd,
data_tyd AS data_8
FROM tyds
WHERE user_tyd = 3
AND action_tyd = 8) Agg_3
ON Agg_3.product_tyd = tyds.product_tyd
INNER JOIN (SELECT product_tyd,
data_tyd AS data_9
FROM tyds
WHERE user_tyd = 3
AND action_tyd = 9) Agg_4
ON Agg_4.product_tyd = tyds.product_tyd
WHERE tyds.user_tyd = 3
AND tyds.action_tyd = 1
GROUP BY tyds.product_tyd
All this jointures because i need to get a lot of things :
I define an id_user in tyds.user_tyd = 3
tyds.action_tyd = 1 because i want to group by the tyds.product_tyd WHERE the previous id_user as an tyds.action_tyd = 1.
Then i want :
-data_8 is the value of tyds.data_tyd WHERE user_tyd = 3 AND action_tyd = 8
-same for data_9
-for AVG and COUNT i want to skip the tyds.user_tyd condition and only group by id_product.
Actually, this query is working but i think it’s really heavy and has too much SELECT…
I put a similar question a month ago but i had to review my architecture so i’m sorry…
Thanks a lot.
e1 : i use MySQL
You don’t actually need all of those joins and subqueries; you can eliminate most of them by moving logic from
WHERE-clauses into the field-list, usingCASEexpressions:(Note: the
MAX(...)in the third and fourth lines are just a way of forcing a non-null value to be preferred over a null one.)You’ll have to test to see if this is actually faster, but I’m betting that it is.