mysql 15-16章联结

###########################
#第十五章 联结表 
###########################

##where创造联结
select vend_name,prod_name,prod_price from vendors,products
where vendors.vend_id=products.vend_id
order by vend_name,prod_name;

##内部联结 等值联结 inner join...on...
select vend_name,prod_name,prod_price
from vendors inner join products 
on vendors.vend_id=products.vend_id;

##联结多个表 
select prod_name,vend_name,prod_price,quantity
from orderitems,products,vendors
where products.vend_id=vendors.vend_id
and orderitems.prod_id=products.prod_id
and order_num=20005;

##回顾十四章例子 
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='TNT2'));
                                   
#等价写法 
select cust_name,cust_contact 
from customers ,orders,orderitems#后面两个也要写上 因为过滤条件用到了虽然前面没用到 
where customers.cust_id=orders.cust_id
and orders.order_num=orderitems.order_num
and orderitems.prod_id='TNT2';                                 
                                   
                                   
##########################
#第十六章 创建高级联结 
##########################
                                   
#使用表别名 
select cust_name,cust_contact 
from customers as c,orders as o,orderitems as oi
where c.cust_id=o.cust_id
and o.order_num=oi.order_num
and oi.prod_id='TNT2';                              
                                   
##使用不同类型的联结 
#自联结
select prod_id,prod_name from products
where vend_id=(select vend_id from products where prod_id='DTNTR');
#此查询需要的两张表是一张表 需要两个别名 
select p1.prod_id,p1.prod_name 
from products as p1,products as p2
where p1.vend_id = p2.vend_id
and p2.prod_id='DTNTR';                                 
   
#自然连结 ????
#自然连接就是自动按同名同类型字段进行内连接并在结果集中去掉重复的连接字段。
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='FB';

#外部联结 
select customers.cust_id,orders.order_num
from customers inner join orders
on customers.cust_id=orders.cust_id;
#left join指定包括所有行的表在左边 没有匹配的就返回null
select customers.cust_id,orders.order_num
from customers left outer join orders
on customers.cust_id=orders.cust_id;

##使用带聚集函数的查询 
select customers.cust_name,
       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;

select customers.cust_name,
       customers.cust_id,
       count(orders.order_num) as num_ord
from customers left join orders
on customers.cust_id=orders.cust_id
group by customers.cust_id;



你可能感兴趣的:(mysql)