一、定义
Union操作符用于合并两个或多个SELECT语句的结果集;
注:1. Union连接的Select语句之间必须拥有相同数量的列;
2. 列也必须拥有相似的数据类型;
3. 每条 SELECT 语句中的列的顺序必须相同;
INTERSECT选取出表中共有的部分,语法和Union一样;
二、详细例子说明
1. 创建Employee_USA和Employee_China表,并插入数据:
DROP TABLE IF EXISTS `Employee_USA`; CREATE TABLE `Employee_USA` ( `ID_E` int(11) NOT NULL AUTO_INCREMENT, `FistName` varchar(32) COLLATE utf8_bin DEFAULT NULL, `LastName` varchar(32) COLLATE utf8_bin DEFAULT NULL, `Age` int(11) DEFAULT NULL, `City` varchar(32) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`ID_E`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Records of Employee_USA -- ---------------------------- INSERT INTO `Employee_USA` VALUES ('1', 'Adams', 'John', '21', 'Phoenix'); INSERT INTO `Employee_USA` VALUES ('2', 'San', 'Zhang', '23', 'Shanghai'); INSERT INTO `Employee_USA` VALUES ('3', 'Carter', 'Thomas', '26', 'Denver');
DROP TABLE IF EXISTS `Employee_China`; CREATE TABLE `Employee_China` ( `ID_E` int(11) NOT NULL AUTO_INCREMENT, `LastName` varchar(32) COLLATE utf8_bin DEFAULT NULL, `FistName` varchar(32) COLLATE utf8_bin DEFAULT NULL, `Age` int(11) DEFAULT NULL, `City` varchar(32) COLLATE utf8_bin DEFAULT NULL, PRIMARY KEY (`ID_E`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; -- ---------------------------- -- Records of Employee_China -- ---------------------------- INSERT INTO `Employee_China` VALUES ('1', 'Li', 'Yuan', '28', 'Beijing'); INSERT INTO `Employee_China` VALUES ('2', 'Zhang', 'San', '22', 'Shanghai'); INSERT INTO `Employee_China` VALUES ('3', 'Li', 'Si', '35', 'Shenzhen');
以上表格显示为:
Employee_USA表:
Employee_China表:
2. Union语句,结果集中字段数据相同:
SELECT FistName, lastName, City FROM Employee_China UNION SELECT FistName, lastName, City FROM Employee_USA
执行结果:
3. Union语句,结果集中字段数据不同:
SELECT FistName, lastName, Age, City FROM Employee_China UNION SELECT FistName, lastName, Age, City FROM Employee_USA
执行结果:
4. Union All
SELECT FistName, lastName, City FROM Employee_China UNION ALL SELECT FistName, lastName, City FROM Employee_USA
执行结果:
三、Union, Union All结论:
从以上两个语句的执行情况可以看出:
1. Union会合并结果集相同的数据,而不管该数据在数据表中是否有不同的字段数据;
2. Union All显示所有的数据,不管结果集是否相同;
四、Intersect示例
SELECT FistName, lastName FROM Employee_China INTERSECT SELECT FistName, lastName FROM Employee_USA
1. 在Mysql运行结果如下:
五、Intersect结论
1. Mysql不支持Intersect;
2. 请自行测试Oracle,谢谢