SQL优化案例分享(一)union和union all

本文介绍了两种SQL查询优化的方法:一是通过使用union替代union all减少子查询中的重复数据;二是当合并多个查询结果时,若能确保数据不重复,则推荐使用union all以提升效率。

#优化前:110s,优化后:0.185s

要善于查看执行计划:unique的cost是最大的,占到了很多。

情形一:子查询中多用union。

我们都知道,最小范围unique可以提高速度,因此在sql子查询中,尽可能避免写union all,如果逻辑上改变不了,那么就改成union先实现内部排重;例子:

select .... from A

  left join (

      (select .... from B)B1  union (select ... from C)C1 on B1.id=C1.id 

   )B2 

     on A.id=B2.id

情形二:非子查询查询结果合并union all要比union 效率高,但是业务上要保证各个部分数据不重复。

例子:

select .... from A

union all

select .... from B

union all

...

 

unionunion all都是用于合并两个或多个select语句的结果集的操作符,但它们之间有个重要的区别:union会自动去重,而union all不会。 举个具体的SQL案例: 假设我们有两个表,个是学生表(students),个是教师表(teachers),它们的结构如下: students表: | id | name | age | gender | |----|-------|-----|--------| | 1 | Alice | 18 | F | | 2 | Bob | 19 | M | | 3 | Carol | 20 | F | teachers表: | id | name | age | gender | |----|---------|-----|--------| | 1 | Mr. Lee | 30 | M | | 2 | Ms. Liu | 35 | F | 现在我们想要将这两个表中的所有人员信息合并成个结果集,可以使用以下SQL语句: 1. 使用union操作符: ``` SELECT name, age, gender FROM students UNION SELECT name, age, gender FROM teachers; ``` 执行以上SQL语句后,得到的结果集如下: | name | age | gender | |---------|-----|--------| | Alice | 18 | F | | Bob | 19 | M | | Carol | 20 | F | | Mr. Lee | 30 | M | | Ms. Liu | 35 | F | 可以看到,使用union操作符后,结果集中自动去重,去掉了两个表中重复的gender列为F的记录。 2. 使用union all操作符: ``` SELECT name, age, gender FROM students UNION ALL SELECT name, age, gender FROM teachers; ``` 执行以上SQL语句后,得到的结果集如下: | name | age | gender | |---------|-----|--------| | Alice | 18 | F | | Bob | 19 | M | | Carol | 20 | F | | Mr. Lee | 30 | M | | Ms. Liu | 35 | F | 可以看到,使用union all操作符后,结果集中保留了两个表中所有的记录,没有去重。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子涵先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值