Day-12:创建高级联结


1、使用表别名
例子:
select cust_name, cust_contact

from customers 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';

/*
cust_name, cust_contact

Fun4All Denise L. Stephens
The Toy Store Kim Howard
*/
说明:表别名只在查询中使用,不返回到客户端。
2、使用不同类型的联结
2、1自联结
例子:给Jim Jones公司的所有顾客发信件
方法一:子查询
select cust_id, cust_name, cust_contact

from customers

where cust_name = (select cust_name

from customers

where cust_contact = 'Jim Jones');
方法二:自联结
select C1.cust_id, C1.cust_name, C1.cust_contact

from customers as C1, customers as C2

where C1.cust_name = C2.cust_name

and C2.cust_contact = 'Jim Jones';

/*
cust_id cust_name cust_contact
1000000003 Fun4All Jim Jones
1000000004 Fun4All Denise L. Stephens
*/
说明:一般DBMS处理联结比子查询快,Oracle 没有as,取别名直接 customers C.
2、2自然联结
自然联结排除多次出现,使每一列只返回一次,自然联结要求你只能选择那些唯一的列,
一般通过对一个表使用通配符(*),而对其他表的列使用明确的子集来完成。
例子:
select C.*, O.order_num, O.order_date, OI.prod_id, OI.quantity, OI.item_price

from customers 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';

/*
1000000004 Fun4All 829 Riverside Drive Phoenix AZ 88888 USA
1000000005 The Toy Store 4545 53rd Street Chicago IL 54545 USA

*/

2、3外联结
左外联结
select customers.cust_id, orders.order_num

from customers left outer join orders

on customers.cust_id = orders.cust_id;

/*cust_id order_num
1000000001 20005
1000000003 20006
1000000004 20007
1000000005 20008
1000000001 20009
1000000002

*/
右外联结
select customers.cust_id, orders.order_num

from customers right outer join orders

on customers.cust_id = orders.cust_id;
/*
cust_id order_num
1000000001 20005
1000000003 20006
1000000004 20007
1000000005 20008
1000000001 20009
*/
2、4使用带聚集函数的联结
例子:查询所有顾客及每个顾客的订单数
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;
/*
cust_id, num_ord

1000000001 2
1000000003 1
1000000004 1
1000000005 1*/
例子:左外联结所有顾客订单
select customers.cust_id, count(orders.order_num) as num_ord

from customers left outer join orders

on customers.cust_id = orders.cust_id

group by customers.cust_id;

/*
cust_id, num_ord

1000000001 2
1000000002 0
1000000003 1
1000000004 1
1000000005 1

*/

原文地址:https://www.cnblogs.com/jp-mao/p/6582420.html