mysql 集合操作UNION DISTINCT和UNION ALL

来源:互联网 发布:gif压缩 知乎 编辑:程序博客网 时间:2024/05/22 13:00

MySQL数据库支持两种集合操作:UNION DISTINCT和UNION ALL。 UNION DISTINCT组合两个输入,并应用DISTINCT过滤重复项,一般可以直接省略DISTINCT关键字,直接使用UNION。 在多个SELECT语句中,对应的列应该具有相同的字段属性,且第一个SELECT语句中被使用的字段名称也被用于结果的字段名称。

建表数据

为了更好的理解,造了下面mysql的两张表和一些数据。两张表中的数据其实是一样的(比较懒了,^_^),表及表字段略加改动。

create table name(    id int(4) not null auto_increment comment 'key',    name varchar(16) not null comment 'Name',    agend int(1) comment 'agend',    PRIMARY key(id))ENGINE=INNODB DEFAULT charset='utf8' comment 'name';insert into name(name,agend) values('ck1','1');insert into name(name,agend) values('ck2','0');insert into name(name,agend) values('ck3','1');insert into name(name,agend) values('ck4','0');insert into name(name,agend) values('ck1','1');create table name2(    id2 int(4) not null auto_increment comment 'key',    name2 varchar(16) not null comment 'Name',    agend2 int(1) comment 'agend',    PRIMARY key(id2))ENGINE=INNODB DEFAULT charset='utf8' comment 'name2';insert into name2(name2,agend2) values('ck1','1');insert into name2(name2,agend2) values('ck2','0');insert into name2(name2,agend2) values('ck3','1');insert into name2(name2,agend2) values('ck4','0');insert into name2(name2,agend2) values('ck1','1');

union distinct

其实union 相当于 union distinct,个人觉得写全比较好,不要偷懒。
当A查询中有数据a,B查询中有数据a,对两个查询使用union distinct方法,那么查询结果只有一条数据a记录。

举例如下:

(select * from name where name = 'ck1' AND agend = '1') UNION DISTINCT (SELECT * from name2 where agend2 = '1');union distinct

union distinct

union all

当A查询中有数据a,B查询中有数据a,对两个查询使用union all方法,那么查询结果会出现两条数据a。

举例如下:

(SELECT * from name2 where agend2 = '1') UNION ALL (select * from name where name = 'ck1' AND agend = '1');

union all

提示

1、当A查询中有数据a,B查询中有数据a,不管对两个查询使用union all/distinct方法,查询结果的字段展示是根据union all/distinct前的查询结果字段展示的。例如上文union all,查询语句为:

(SELECT * from name2 where agend2 = '1') UNION ALL (select * from name where name = 'ck1' AND agend = '1');

那么展示的字段是 name2 表中的字段。上图已标注。
2、union all 在使用UNION DISTINCT的时候,由于向临时表中添加了唯一索引,插入的速度显然会因此而受到影响。如果确认进行UNION操作的两个集合中没有重复的选项,最有效的办法应该是使用UNION ALL。

参考文章:http://www.3lian.com/edu/2015/05-23/216050.html

0 0
原创粉丝点击