尝试将来自不同表的多个总和与每个表的不同where条件相加。
这是我的3笔钱:
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';
结果必须为(first sum) - (second sum) - (third sum)
。
答案 0 :(得分:3)
MySQL支持基本运算符,因此您应该能够执行以下简单的操作:
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');
我确信这可以进行优化,但这应该可以满足您的需求(如果没有关于关系的更好信息,那么优化就很困难了。)
答案 1 :(得分:1)
您可以将每个查询子查询设置为执行所需求和的外部查询:
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');