我有三个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
Run Code Online (Sandbox Code Playgroud)
我需要的是所有三个值的总和. sum(field_one)+sum(field_two)+sum(field_three).反正有没有在一个声明中这样做?
你可以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
Run Code Online (Sandbox Code Playgroud)
您无需使用Union即可执行此操作
样品查询
select( (select 15) + (select 10) + (select 20))
Run Code Online (Sandbox Code Playgroud)
您的查询
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)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2470 次 |
| 最近记录: |