If I need to get five+ different SUM values with similar WHERE conditions, is the best (maybe only) way to do it through one query with five subqueries? For example, my query is:
SELECT user,
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 1 AND user = 1 AND date = x) AS one,
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 2 AND user = 1 AND date = x) AS two,
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 3 AND user = 1 AND date = x) AS three,
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 4 AND user = 1 AND date = x) AS four,
(SELECT SUM(amount) FROM table t, table2 t2 WHERE t.table2_id = t2.id AND table2.type = 5 AND user = 1 AND date = x) AS five
FROM table
WHERE user = 1
So far my queries have been very quick but I’m worried about the implication of five+ sub-queries when there’s many more records.
And out of curiosity does one query like this with five sub-queries have a performance advantage / dis-advantage over five individual queries? I was assuming it’s faster because it’s only one trip to the database vs 5?
EDIT: There is a table 2 of about 60 records that are used to classify the thousands of records in table 1. Each record in table 2 is categorized by a type value of 1 – 5 (which is what I’m using to group items I want the SUM of).
Rewritten:
I understand your query is pseudo but it has a hanging
WHERE userwithout aFROMclause. As for performance, the above goes through the table in one pass. The 5x subquery form would have taken 5 passes, but should not be significantly slower if proper indexes are available.