表的集合运算

表,视图  和查询的执行结果表可以理解成“记录的集合”。

1.求并集 —— union

对两张表中的记录求并集,使用关键字  union.

select   t1.name  ,  t1.sex  from  tb_student1  t1
union
select   t2.name  ,  t2.sex  from  tb_student2  t2;

对于重复的记录,会自动进行去重。如果想要不进行去重的结果,使用 union  all。

select   t1.name  ,  t1.sex  from  tb_student1  t1
union  all
select   t2.name  ,  t2.sex  from  tb_student2  t2;

表的集合运算的注意事项 : (求交集  ,求差集同样要遵守)
注意事项1:作为运算对象的 记录的列数必须相同。

注意事项2:再列数相同的情况下,每列的数据类型应该一致。

注意事项3:求完并集之后,才进行排序。如果要进行排序,order by子句只能再最后使用一次。

2.求交集  —— intersect

对两张表中的记录求交集 ,使用关键字 intersect   (MySQL数据库暂不支持)

select   t1.name  ,  t1.sex   from  tb_student  t1
intersect   
select   t2.name  ,  t2.sex   from  tb_student  t2;

intersect应用于两张表 ,将选取出它们当中的公共记录。

同样,如果需要保留重复行时 ,需要使用 intersect  all.

3.求差集  —— except 

select  t1.name  ,  t1.sex  from  tb_student1  t1
except  
select  t2.name  ,  t2.sex  from  tb_student2  t2;

假设前面的select查询,得到的结果表1包含5条记录,后面的select查询,得到的结果表2包含3条记录。

这两张表,根据name,sex来判断,有两条记录是相同的。那么就在 结果表1中去除掉这两条记录,得到最终的结果表。

 求差集,可以看成是先求两表的交集记录,然后在被减表中去掉交集记录的过程。

原文地址:https://www.cnblogs.com/wangliyue/p/4184602.html