SQL查询之组合查询
2016-05-23 14:56
232 查看
组合查询
SQL允许执行多个查询(多条SELECT语句),并将结果作为一个结果集返回.这些组合查询成为并(union)或复合查询(compound query)有两种情况需要使用组合查询:
在一个查询中从不同的表返回结构数据.对一个表执行多个查询,按一个查询返回数据.
组合查询一般使用union关键字,或者多条where语句
使用多条where语句的查询,也可以看做是组合查询
-- 使用union作为组合关键字进行组合查询 select cust_name ,cust_contact,cust_email from customers where cust_state in ('IL','IN','MI') union select cust_name ,cust_contact,cust_email from customers where cust_name='Fun4All'; -- 与使用多条where语句的组合查询结果一样 select cust_name ,cust_contact,cust_email from customers where cust_state in('IL','IN','MI') or cust_name='Fun4All'; /* cust_name, cust_contact, cust_email Fun4All Jim Jones jjones@fun4all.com Fun4All Denise L. Stephens dstephens@fun4all.com The Toy Store Kim Howard Village Toys John Smith sales@villagetoys.com */
使用 union关键字的的规则
1.union必须由两条或者两条以上select语句组成,语句之间使用union关键字分割
2. union中每个查询必须包含相同的列,表达式,或聚集函数,各个列不需要以相同的顺序列出.
3.列数据类型必须兼容,类型不必完全相同,但必须是 DBMS可以隐含转换的类型.
使用union进行组合查询会自动去除重复的行,使用union all关键字,会显示所有匹配的行,不会去除重复.
-- 使用union all作为组合关键字进行不会去除重复的行 select cust_name ,cust_contact,cust_email from customers where cust_state in ('IL','IN','MI') union all select cust_name ,cust_contact,cust_email from customers where cust_name='Fun4All'; /* cust_name, cust_contact, cust_email Village Toys John Smith sales@villagetoys.com Fun4All Jim Jones jjones@fun4all.com The Toy Store Kim Howard Fun4All Jim Jones jjones@fun4all.com Fun4All Denise L. Stephens dstephens@fun4all.com */
使用order by 对结果集进行排序.
order by语句只能出现在最后一条select 语句后面,并且只能出现一次.
-- 升序排列所有结果集 select cust_name ,cust_contact,cust_email from customers where cust_state in ('IL','IN','MI') union all select cust_name ,cust_contact,cust_email from customers where cust_name='Fun4All' order by cust_name asc; /* cust_name, cust_contact, cust_email Fun4All Jim Jones jjones@fun4all.com Fun4All Jim Jones jjones@fun4all.com Fun4All Denise L. Stephens dstephens@fun4all.com The Toy Store Kim Howard Village Toys John Smith sales@villagetoys.com */
相关文章推荐
- Memcache Brief Intro
- 数据库Sharding的基本思想和切分策略
- Oracle Exists用法
- Centos7下安装php-redis扩展及简单使用
- MySql实现分页查询的SQL,mysql实现分页查询的sql语句
- MySql实现分页查询的SQL,mysql实现分页查询的sql语句
- MySql实现分页查询的SQL,mysql实现分页查询的sql语句
- MYSQL添加新用户 MYSQL为用户创建数据库 MYSQL为新用户分配权限
- SQL Server的下载安装连接使用过程
- oracle转db2出现的问题
- Oracle 中count(1) 和count(*) 的区别
- mysql基本常用命令
- sql语法
- SQL LEFT JOIN 关键字
- 使用开单引号对SQL语句中的表字段名转义
- 使用存储过程
- Mongodb中MapReduce实现数据聚合方法详解
- 安装Sql server2008R2 Express 碰到 system ,version=4.0错误
- plsql学习
- Mongodb聚合函数count、distinct、group如何实现数据聚合操作