union 与 unionall 的区别

union 和 union all 都是对返回的结果集进行合并,那么它们有没有什么区别呢?

先看一下使用 union 和 union all 查询返回的结果集

// 使用 union 进行查询
select * from t_merchant_tmp where F_id in (34,28,13)
union
select * from t_merchant_tmp where F_id in (13,28,55);

// 使用 union all 进行查询
select * from t_merchant_tmp where F_id in (34,28,13)
union all
select * from t_merchant_tmp where F_id in (13,28,55);

使用 union 返回了 4 条记录,而使用 union all 返回了 6 条记录

1、union 会对结果集进行去重,并且按照默认的排序规则进行排序(这里使用的默认排序规则是主键)

2、union all 只是对结果集进行简单的合并,不会去除重复元素,也不会进行排序

从上面的结论可以得出,union 会额外进行去重、排序等步骤,性能较差,如果确定合并返回的结果集中没有重复的元素,那么就使用 union all

 

 

posted @ 2022-04-24 16:31  变体精灵  阅读(169)  评论(0编辑  收藏  举报