笔记来源:DATAWHALE - 一个热爱学习的社区 (linklearner.com)
目录
1.表的集合运算
表的加法
Union去重
假设连锁店想要增加成本利润率超过 50%或者售价低于 800 的货物的存货量, 请使用 UNION 对分别满足上述两个条件的商品的查询结果求并集。
UNION ALL--包含重复行的集合运算
隐式数据类型转换
隐式类型转换来将两个类型不同的列放在一列里显示, 例如字符串和数值类型:
以下代码可以正确执行, 说明时间日期类型和字符串,数值以及缺失值均能兼容。
表的交集
使用inner join
注意:缺失值是不能用等号进行比较的!
表的差集
-- 使用 NOT IN 子句的实现方法
SELECT * FROM Product
WHERE product_id NOT IN (SELECT product_id FROM Product2)
表的对称差
两个集合A,B的对称差是指那些仅属于A或仅属于B的元素构成的集合。
2.连接(JOIN)
内连接--INNER JOIN
查找两张表都有的公共部分
内连结与关联子查询
找出每个商品种类当中售价高于该类商品的平均售价的商品.
关联子查询的做法:
内连接的做法:
外连结--OUTER JOIN
内连结会丢弃两张表中不满足 ON 条件的行,和内连结相对的就是外连结。
外连结会根据外连结的种类有选择地保留无法匹配到的行。
按照保留的行位于哪张表,外连结有三种形式: 左连结, 右连结和全外连结。
左连结会保存左表中无法按照 ON 子句匹配到的行, 此时对应右表的行均为缺失值;
右连结则会保存右表中无法按照 ON 子句匹配到的行, 此时对应左表的行均为缺失值;
而全外连结则会同时保存两个表中无法按照 ON子句匹配到的行, 相应的另一张表中的行用缺失值填充。
多表连结

3.练习
-- 4.1 找出 product 和 product2 中售价高于 500 的商品的基本信息。
select * from product where sale_price>500 union select * from product2 where sale_price>500;
-- 4.2 借助对称差的实现方式, 求product和product2的交集。
select * from product where product_id in (select product_id from product2);
-- 4.3 每类商品中售价最高的商品都在哪些商店有售 ?
select p.product_id,sp.shop_name,p.product_type,max(p.sale_price) as max_price from product as P inner join shop_product sp on P.product_id = sp.product_id group by p.product_type,sp.shop_name; -- 4.4 分别使用内连结和关联子查询每一类商品中售价最高的商品。
-- 1.内连接
select product_name from product inner join (select product_type,max(sale_price) max_price from (select * from product union select * from product2) t1 group by product_type) p1 on product.product_type=p1.product_type and product.sale_price=p1.max_price;
-- 2.关联子查询
select p1.product_name from product p1 where sale_price= (select max(sale_price) from product p2 where p1.product_type=p2.product_type);
-- 4.5 用关联子查询实现:在 product 表中,取出 product_id, product_name, sale_price, -- 并按照商品的售价从低到高进行排序、对售价进行累计求和。
select p1.product_id,p1.product_name,p1.sale_price ,(select sum(p2.sale_price) from product p2) sum_price from product p1 order by sale_price ;