MySQL 学习4

一、表的加减法

  1. 集合运算
    集合 在数据库领域表示记录的集合
    在标准sql中,分别对检索结果使用 UNION, INTERSECT, EXCEPT (集合运算符)来将检索结果进行并,交和差运算
  2. 表的加法–union
    求并集,合并和去重,union 等集合运算符通常都会除去重复的记录.
sELECT  product_id,product_name,product_type,sale_price,purchase_price
  FROM product 
  where sale_price<800
  union
  SELECT  product_id,product_name,product_type
       ,sale_price,purchase_price
  FROM product 
 WHERE sale_price>1.5*purchase_price;

在这里插入图片描述
union all合并不去重

  1. 交运算–intersect
    集合的交,就是两个集合的公共部分
SELECT product_id, product_name
  FROM product
  
INTERSECT
SELECT product_id, product_name
  FROM product2
  1. 表的减法–except
    就是在集合A中减去2个集合的交集
    使用not in 谓词,基本上可以实现和sql标准语法中的except运算相同的效果.
--找出只存在于product表但不存在于product2表的商品
SELECT * 
  FROM product
 WHERE product_id NOT IN (SELECT product_id 
                            FROM product2)
  1. 对称差并集减去交集
    两个集合A,B的对称差是指那些仅属于A或仅属于B的元素构成的集合
    直观上就能看出来,两个集合的对称差等于 A-B并上B-A
--用 NOT IN 实现两个表的差集
select *
from table1 
where name not in (select name from table2)
union
select *
from table2
where name not in (select name from table1)

二、连结

  1. 内连结–inner join
    使用某种关联条件, 将其他表中的列添加过来,进行“添加列”的集合运算
    A inner join B on ‘条件’
select *
from table1 join table2 on table1.name = table2.name
  1. 多表连结
    就是连结3张及3张以上的表
select *
from table1 inner join table2 on table1.name=table2.name inner 
	join table3 on table1.name=table3.name
where name='zs'
  1. 外连结—outer join
    左连结,右连结,全外连结
    左连结:左连结会保存左表中无法按照 on 子句匹配到的行,此时对应右表的行均为缺失值
    右连结:右连结会保存右表中无法按照 on 子句匹配到的行,此时对应左表的行均为缺失值
    全外连结:全外连结会同时保存两个表中无法按照 on子句匹配到的行,相应的另一张表中的行用缺失值填充
-- 左连结     
FROM <tb_1> LEFT  OUTER JOIN <tb_2> ON <condition(s)>
-- 右连结     
FROM <tb_1> RIGHT OUTER JOIN <tb_2> ON <condition(s)>
-- 全外连结
FROM <tb_1> FULL  OUTER JOIN <tb_2> ON <condition(s)>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值