mysql: join

/***************
 * join tables *
 ***************/
 
-- list all sales for FLEX and BLAZE;
select * from product;
select * from sales;
-- what happens without a.product_id=b.product_id;
-- use table alias;

 
 
-- practice: list all transactions with Amazon;
select s.*,c.*
from sales s, client c
where s.client_id = c.client_id and c.name = 'Amazon';


-- list all sales with msrp > 100 and quantity >= 10, or quality >= 100; ignore non-existing product_id in PRODUCT;
-- ignore non-existing product_id in PRODUCT;
select s.*,p.*
from sales s, product p
where s.product_id = p.product_id and ((p.msrp > 100 and s.quantity >= 10) or (s.quantity >= 100));


/***************
*     Join     * 
***************/

-- show all transactions with shipping status;
/* inner join */
select s.*,sh.*
from sales s
inner join shipping sh
where s.tran_id = sh.tran_id;

/* left join */
select s.*,sh.*
from sales s
left join shipping sh
on s.tran_id = sh.tran_id;

-- list all shipments with shipping status; show client_id and product_id if exists;
/* right join */
select s.*,sh.*
from sales s
right join shipping sh
on s.tran_id = sh.tran_id;

-- list all shipping status with client_id and product_id;
/* right join */

-- list all sales and shipping status in one table;


-- list all transactions and shipping status in one table;
/* full join */
-- select s.tran_id as trn_id, s.client_id, s.product_id, sh.status
-- from shipping sh
-- full join sales s
-- on s.tran_id = sh.tran_id
-- ;
-- MySQL doesn't support full join!


/*********************
 *    set operators  *
 *********************/
-- union;
select * from sales;
select * from sales where tran_id > 1
union
select * from sales where tran_id > 2;

-- union all
select * from sales;
select * from sales where tran_id > 1
union all
select * from sales where tran_id > 2;

  

转载于:https://www.cnblogs.com/tabCtrlShift/p/9236444.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值