Reputation:
Trying to sum multiple sums from different tables with different where conditions for each table.
Here's my 3 sums:
SELECT SUM(1column2) FROM table1 WHERE 1column1 = '0';
SELECT SUM(1column4) FROM table1 WHERE 1column3 = '0';
SELECT SUM(2column2) FROM table2 WHERE 2column1 = '0' AND 2column3 = 'w' AND 2column4 != 'f';
The result needs to be (first sum) - (second sum) - (third sum)
.
Upvotes: 0
Views: 1586
Reputation: 1128
MySQL supports basic operators, so you should be able to do something as simple as:
SELECT (SELECT SUM(1column2) FROM table1 WHERE 1column1 = '0') - (SELECT SUM(1column4) FROM table1 WHERE 1column3 = '0') - (SELECT SUM(2column2) FROM table2 WHERE 2column1 = '0' AND 2column3 = 'w' AND 2column4 != 'f');
I'm sure this can be optimized, but that should give you what you need (and without better information on the relationships, optimization would be difficult).
Upvotes: 3
Reputation: 125865
You could just make each of those queries subqueries to an outer query that performs your desired summation:
SELECT
(SELECT SUM(1column2) FROM table1 WHERE 1column1 = '0')
- (SELECT SUM(1column4) FROM table1 WHERE 1column3 = '0')
- (SELECT SUM(2column2) FROM table2 WHERE 2column1 = '0'
AND 2column3 = 'w' AND 2column4 != 'f');
Upvotes: 1