Day-13:组合查询


1、创建组合查询
使用union把多条select语句的结果组成一个结果集。
例子
方法一:
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';
方法二:
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
Village Toys John Smith sales@villagetoys.com
Fun4All Jim Jones jjones@fun4all.com
The Toy Store Kim Howard
Fun4All Denise L. Stephens dstephens@fun4all.com
*/

2、对组合结果排序
在最后一个select语句的最后使用order by,则结果集可以排序输出。
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'

order by cust_name, cust_contact;
/*
cust_name, cust_contact, cust_email
Fun4All Denise L. Stephens dstephens@fun4all.com
Fun4All Jim Jones jjones@fun4all.com
The Toy Store Kim Howard
Village Toys John Smith sales@villagetoys.com
*/

posted @ 2017-03-19 21:36  起航追梦人  阅读(122)  评论(0编辑  收藏  举报