开发者

Adding the results of multiple SQL selects?

I have three SQL selects, the results of which I need to add together. Two of the three use fairly complex joins.

select sum(field_one) from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=:id开发者_Go百科
select sum(field_two) from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=:id
select sum(field_three) from t_e where t_e.user_id=:id

What I need is the sum of all three values. sum(field_one)+sum(field_two)+sum(field_three). Is there anyway to do this in a single statement?


You could UNION ALL them.
Do not use UNION, since it omits duplicate values (5+5+5 would result in 5).

Select Sum(s)
From
(
  Select Sum(field_one) As s ...
  Union All
  Select Sum(field_two) ...
  Union All
  Select Sum(field_three) ...
) x


You can do this without using Union like this

Sample Query

select( (select 15) + (select 10) + (select 20)) 

Your Query

select
(
    (select sum(field_one) from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=:id) +
    (select sum(field_two) from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=:id) +
    (select sum(field_three) from t_e where t_e.user_id=:id) 
)


You can use a UNION and a subselect to do that:

select sum(`sum`) FROM
(
  select sum(field_one) as `sum` from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=:id
  UNION ALL
  select sum(field_two) from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=:id
  UNION ALL
  select sum(field_three) from t_e where t_e.user_id=:id
) as x;

Edit: Updated my answer to use UNION ALL, as suggested by Peter Lang.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜