【问题标题】:Adding the results of multiple SQL selects?添加多个 SQL 选择的结果?
【发布时间】:2010-10-05 19:46:42
【问题描述】:

我有三个 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)。有没有办法在一个语句中做到这一点?

【问题讨论】:

  • 尝试使用这个 select( (select 15) + (select 10) + (select 20)) 逻辑在下面检查我的答案

标签: sql mysql join


【解决方案1】:

你可以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】:

    你可以不用像这样使用 Union 来做到这一点

    示例查询

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

    【讨论】:

    • +1: 应该适用于 MySQL 和 SQL-Server,但不是 Oracle,但这不是问题 :)
    • 我不知道 oracle 反正我也不知道 MySQL :P 也许我必须在不久的将来尝试学习它
    【解决方案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 的答案。

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 2023-03-24
      • 2021-06-17
      • 2021-06-08
      • 2016-02-25
      • 2012-06-22
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      相关资源
      最近更新 更多