我理解的表连接, 应该是from 表一 union 表二, 但是现在表一,表二都是查询的结果, 为什么不要加给查询的结果加个括号, 这样表示先计算查询的结果, 再连接.
但是这段代码可以执行, 是不是说明 union 默认的就是先等所有的查询结束之后再拼接? 请大神解答, 有可能我的描述不是很清楚.
题干:把2019年每个用户的支付和退款金额汇总起来, 有两个表源: user_trade 用户交易表, user_refund用户退款表, 分别记录的是用户交易的金额和退款的金额
教材给的代码是这样的:
select a.user_name,
sum(a.total_amount),
sum(a.refund_amount)
from
(select user_name,
sum(pay_amount) total_amount,
0 as refund_amount
from user_trade
where year(dt)=2019
group by user_name
union all
select user_name,
0 as total_amount,
sum(refund_amount) refund_amount
from user_refund
where year(dt)=2019
group by user_name)a
我的理解应该是这样的:
select a.user_name,
sum(a.total_amount),
sum(a.refund_amount)
from
((select user_name,
sum(pay_amount) total_amount,
0 as refund_amount
from user_trade
where year(dt)=2019
group by user_name)
union all
(select user_name,
0 as total_amount,
sum(refund_amount) refund_amount
from user_refund
where year(dt)=2019
group by user_name))a
对于这个问题,需要了解一些关于 SQL 的语法规则。在 SQL 中,UNION 操作符将两个查询的结果集合并为一个结果集,并且默认会去重。而当使用 UNION ALL 操作符时,不会进行去重,将直接将两个查询的结果集合并在一起。
对于这个查询语句中的子查询,虽然可以使用括号来明确它们的优先级,但是并不是必需的。因为在 SQL 中,UNION 或 UNION ALL 操作的优先级比子查询更高,所以子查询中的两条 SELECT 语句会首先合并到一起,然后再将结果与外层的 SELECT 语句进行联接。
因此,即使不使用括号,以上两个查询语句也可以正确执行,并按预期生成结果。