代码之家  ›  专栏  ›  技术社区  ›  Daniel Bingham

添加多个SQL选择的结果?

  •  1
  • Daniel Bingham  · 技术社区  · 15 年前

    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 回复  |  直到 15 年前
        1
  •  8
  •   Peter Lang    15 年前

    你可以的 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
    
        2
  •  5
  •   Thakur    15 年前

    你不需要像这样使用并集就可以做到这一点

    示例查询

    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) 
    )
    
        3
  •  3
  •   Dennis Haarbrink    15 年前

    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;
    

    编辑:根据peterlang的建议,更新了我的答案使用unionall。

    推荐文章