添加多个SQL选择的结果?

时间:2010-10-05 11:15:15

标签: sql mysql join

我有三个SQL选择,我需要将其结果加在一起。三个中的两个使用相当复杂的连接。

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

我需要的是所有三个值的总和。 sum(field_one)+sum(field_two)+sum(field_three)。无论如何都要在一个声明中做到这一点吗?

3 个答案:

答案 0 :(得分:8)

你可以UNION ALL他们 不要使用UNION,因为它会忽略重复值(5+5+5会导致5)。

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

答案 1 :(得分:4)

您可以在不使用此类

的情况下执行此操作

示例查询

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

您的查询

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) 
)

答案 2 :(得分:3)

您可以使用UNION和子选择来执行此操作:

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;

编辑:根据Peter Lang的建议,更新了我使用UNION ALL的答案。