结合数学查询MySQL

时间:2011-07-04 11:46:13

标签: mysql

是否可以将以下查询合并为单个,我基本上对获取上一个查询给出的结果感兴趣。

#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;

2 个答案:

答案 0 :(得分:0)

使用子查询,您可以:

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;

答案 1 :(得分:0)

使用UNION制作合成的三行表,然后对其进行汇总。

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

我不确定我理解你的'the_same_num'内容,所以你需要解决这个问题。