添加多个SQL选择的结果?
我有三个SQL选择,需要将它们的结果相加。其中两个使用相当复杂的联接添加多个SQL选择的结果?,sql,mysql,join,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
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)+总和(字段2)+总和(字段3)。在一条语句中是否有这样做的方法?您可以使用一个
联合和一个子选择来实现这一点:
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。您可以使用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。您可以将所有人都联合起来。
不要使用UNION
,因为它会忽略重复的值(5+5+5
将导致5
)
你可以联合所有人他们。
不要使用UNION
,因为它会忽略重复的值(5+5+5
将导致5
)
你可以不用像这样使用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)
)
你可以不用像这样使用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)
)
尝试使用此选择((选择15)+(选择10)+(选择20))逻辑检查下面的我的答案使用此选择((选择15)+(选择10)+(选择20))逻辑检查下面的我的答案+1
:应该适用于MySQL和SQL Server,而不是Oracle,但这不是问题:)我不了解oracle,我也不了解MySQL:P可能是我必须在不久的将来尝试学习它+1
:应该为MySQL和SQL Server工作,但不是oracle,但这不是问题:)我不了解oracle,我也不知道MySQL:P可能是我必须在不久的将来尝试学习它