2011-07-04 99 views
2

可以將下面的查詢合併爲單個查詢,我基本上有興趣獲得最後查詢給出的結果。結合數學查詢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; 
+0

u = v在你的例子中... –

+0

我編輯了這個問題。現在它不會暗示u = v。 – SRM

回答

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; 
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'的東西,所以你需要解決這個問題。

+0

這只是暗示num保持不變。 :) – SRM