参考书籍:《SQL必知必会(第3版)》
#使用子查询(子查询总是从内向外处理)
select cust_name,cust_contact
from Customers
where cust_id in (select cust_id
from Orders
where order_num in (select order_num
from OrderItems
where prod_id='RGAN01'));
——得到订购物品RGAN01的所有客户ID的客户信息
#联结表 (联结的表越多,性能下降得越厉害)
#笛卡尔积(由没有联结条件的表关系返回的结果为笛卡尔积,检索出的行的数目是第一个表中的行数乘以第二个表中的行数)
#内部联结(等值联结)
select vend_name,prod_name,prod_price
from Vendors Inner Join Products
on Venders.vend_id=Products.vend_id;
——(在使用inner join 语法时,联结条件用特定的on子句而不是where子句;ANSI SQL规范首选inner join 语法)
#高级联结
#as(Oracle不支持as关键字,在Oracle中可以不用as,简单地指定列名即可)
select cust_name,cust_contact
from Customer as C, Orders as O, OrderItems as OI
where C.order_num = O.order_num
and OI.order_num = O.order_num
and prod_id = 'RGAN01';
——(使用别名的两个理由:缩短SQL语句、允许在单条select语句中多次使用相同的表)
#自然联结
select C.*,O.order_num,O.order_date,OI.prod_id,OI.quantity,OI.item_price
from Customer as C, Orders as O, OrderItems as OI
where C.cust_id = O.cust_id
and OI.order_num = O.order_num
and prod_id = 'RGAN01';
#外部联结
#左连接右连接(在使用outer join 语法时,必须使用right或left关键字指定包括其所有行的表,;right指出的是 outer join右边的表,而left指出的是outer join 左边的表)
select Customer.cust_id,Orders.order_num
from Customer left outer join Orders
on Customers.cust_id = Orders.cust_id;
或者
select Customer.cust_id,Orders.order_num
from Customer,Orders
where Customers.cust_id *= Orders.cust_id;(SQL服务器中一种简化的外部联结语法,*=为左外部联结操作符、=*为右外部联结操作符)
或者
select Customer.cust_id,Orders.order_num
from Customer,Orders
where Customers.cust_id (+)= Orders.cust_id;(仅由Oracle使用)
——检索出所有客户,包括那些没有订单的客户
#全外部联结(包含来自两个表的不相关联的行,access/mysql/sql server/sybase不支持 full outer join 语法)
select Customer.cust_id,Orders.order_num
from Customer full outer join Orders
on Customers.cust_id = Orders.cust_id;
#使用带聚集函数的联结
select Customers.cust_id,count(Orders.order_num) as num_ord
from Customers inner join Orders
on Customers.cust_id = Orders.cust_id
group by Customers.cust_id;
——检索所有客户以及每个客户所下的订单数
#组合查询(SQL允许多个select语句,并将结果作为单个查询结果集返回)
#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';)
(union中的每个查询必须包含相同的列、表达式或聚集函数;列数据类型必须兼容)
(上面的查询结果集中自动去除了重复的行,如果想反悔所有的匹配行,可使用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';