Combining maths queries MySQL
Is is possible to combine the below queries into single, I am basically interested in getting the result given by the last query.
#This is wrong SQL only intended as pseudocode
SELECT sum(amt) u FROM entry WHERE en_type='some_type' AND num='some_num';
SELECT sum(amt) v FROM entry WHERE en_type='some_other_type' AND num='some_num';
SELECT abal x FROM accounts WHERE num='the_same_num_as_above';
SELECT y = x + v - u开发者_开发知识库;
Using subqueries you can do:
SELECT -(SELECT sum(amt) u FROM entry WHERE en_type='some_type' AND num='some_num')
+ (SELECT sum(amt) v FROM entry WHERE en_type='some_type' AND num='some_num')
+ (SELECT abal x FROM accounts WHERE num='the_same_num_as_above') AS y;
Use UNION to make a synthetic three row table, then summarize it.
SELECT SUM(x) y FROM
(
SELECT sum(amt) AS x FROM entry WHERE en_type='some_type' AND num='some_num'
UNION ALL
SELECT sum(amt) AS x FROM entry WHERE en_type='some_type' AND num='some_num'
UNION ALL
SELECT -abal AS x FROM accounts WHERE num='the_same_num_as_above'
) A
I am not sure I understand your 'the_same_num' stuff, so you'll need to work that out.
精彩评论