欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

初步介绍MySQL中的集合操作

程序员文章站 2024-03-01 11:30:22
啥是集合操作? 通常来说,将联接操作看作是表之间的水平操作,因为该操作生成的虚拟表包含两个表中的列。而我这里总结的集合操作,一般将这些操作看作是垂直操作。mysql数据库...

啥是集合操作?

通常来说,将联接操作看作是表之间的水平操作,因为该操作生成的虚拟表包含两个表中的列。而我这里总结的集合操作,一般将这些操作看作是垂直操作。mysql数据库支持两种集合操作:union distinct和union all。

与联接操作一样,集合操作也是对两个输入进行操作,并生成一个虚拟表。在联接操作中,一般把输入表称为左输入和右输入。集合操作的两个输入必须拥有相同的列数,若数据类型不同,mysql数据库自动将进行隐式转换。同时,结果列的名称由左输入决定。
前期准备

准备测试表table1和table2:

create table table1 
      (aid int not null auto_increment, 
      title varchar(20), 
      tag varchar(10), 
      primary key(aid)) 
      engine=innodb default charset=utf8;

create table table2 
      (bid int not null auto_increment, 
      title varchar(20), 
      tag varchar(10), 
      primary key(bid)) 
      engine=innodb default charset=utf8;

插入以下测试数据:

insert into table1(aid, title, tag) values(1, 'article1', 'mysql');
insert into table1(aid, title, tag) values(2, 'article2', 'php');
insert into table1(aid, title, tag) values(3, 'article3', 'cpp');

insert into table2(bid, title, tag) values(1, 'article1', 'mysql');
insert into table2(bid, title, tag) values(2, 'article2', 'cpp');
insert into table2(bid, title, tag) values(3, 'article3', 'c');

union distinct

union distinct组合两个输入,并应用distinct过滤重复项,一般可以直接省略distinct关键字,直接使用union。

union的语法如下:

select column,... from table1 
union [all]
select column,... from table2
...

在多个select语句中,对应的列应该具有相同的字段属性,且第一个select语句中被使用的字段名称也被用于结果的字段名称。

现在我运行以下sql语句:

(select * from table1) union (select * from table2);

将会得到以下结果:

+-----+----------+-------+
| aid | title  | tag  |
+-----+----------+-------+
|  1 | article1 | mysql |
|  2 | article2 | php  |
|  3 | article3 | cpp  |
|  2 | article2 | cpp  |
|  3 | article3 | c   |
+-----+----------+-------+

我们发现,表table1和表table2中的重复数据项:

|  1 | article1 | mysql |

只出现了一次,这就是union的作用效果。

mysql数据库目前对union distinct的实现方式如下:

  •     创建一张临时表,也就是虚拟表;
  •     对这张临时表的列添加唯一索引;
  •     将输入的数据插入临时表;
  •     返回虚拟表。

因为添加了唯一索引,所以可以过滤掉集合中重复的数据项。这里重复的意思是select所选的字段完全相同时,才会算作是重复的。

union all

union all的意思是不会排除掉重复的数据项,比如我运行以下的sql语句:
(select * from table1) union all (select * from table2);

你将会得到以下结果:

+-----+----------+-------+
| aid | title  | tag  |
+-----+----------+-------+
|  1 | article1 | mysql |
|  2 | article2 | php  |
|  3 | article3 | cpp  |
|  1 | article1 | mysql |
|  2 | article2 | cpp  |
|  3 | article3 | c   |
+-----+----------+-------+

发现重复的数据并不会被筛选掉。

在使用union distinct的时候,由于向临时表中添加了唯一索引,插入的速度显然会因此而受到影响。如果确认进行union操作的两个集合中没有重复的选项,最有效的办法应该是使用union all。