SQL Union 和 Union All 的区别以及二者的性能问题 - 使用Sqlite演示

1 Union 和 Union All 的区别

Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;

Union All:对两个结果集进行并集操作,包括重复行,不进行排序;

    也就是说 Union All的结果中包含重复行;

下面用sqlite来操作一下;

SQL Union 和 Union All 的区别以及二者的性能问题 - 使用Sqlite演示

    看一下 Union All 多了重复行;这是查询结果的区别;

全部的cmd操作如下;

Microsoft Windows [版本 6.1.7601]
Copyright (c) 2010 Microsoft Corporation.  All rights reserved.

S:\>cd sqlite

S:\sqlite>sqlite3 test1.db
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table t1(
   ...> id int not null,
   ...> name varchar(30) not null);
sqlite> create table t2(
   ...> id int not null,
   ...> name varchar(30) not null);
sqlite> Insert into t1 values (1,'姚羽');
sqlite> Insert into t1 values (2,'边兵兵');
sqlite> Insert into t1 values (3,'袁磊');
sqlite>
sqlite> Insert into t2 values (1,'姚羽');
sqlite> Insert into t2 values (2,'柳春平');
sqlite> Insert into t2 values (3,'张永超');
sqlite> Insert into t2 values (4,'刘华健');
sqlite> select * from t1;
1|姚羽
2|边兵兵
3|袁磊
sqlite> select * from t2;
1|姚羽
2|柳春平
3|张永超
4|刘华健
sqlite> select * from Table1 union select * from Table2;
Error: no such table: Table2
sqlite> select * from t1 union select * from t2;
1|姚羽
2|边兵兵
2|柳春平
3|袁磊
3|张永超
4|刘华健
sqlite> select * from t1 union all select * from t2;
1|姚羽
2|边兵兵
3|袁磊
1|姚羽
2|柳春平
3|张永超
4|刘华健
sqlite>

2 union 和 union all 性能上的区别

优先使用UNION ALL,避免使用UNION;UNION 因为会将各查询子集的记录做比较,故比起UNION ALL ,通常速度都会慢上许多。

因为union all不排除重复行,直接进行并操作,所以快。

一般来说,如果使用UNION ALL能满足要求的话,则使用UNION ALL。

还有一种情况,如果业务上能够确保不会出现重复记录,也使用UNION ALL。