一、表的加减法
- 集合运算
集合 在数据库领域表示记录的集合
在标准sql中,分别对检索结果使用 UNION, INTERSECT, EXCEPT (集合运算符)来将检索结果进行并,交和差运算 - 表的加法–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合并不去重
- 交运算–intersect
集合的交,就是两个集合的公共部分
SELECT product_id, product_name
FROM product
INTERSECT
SELECT product_id, product_name
FROM product2
- 表的减法–except
就是在集合A中减去2个集合的交集
使用not in 谓词,基本上可以实现和sql标准语法中的except运算相同的效果.
--找出只存在于product表但不存在于product2表的商品
SELECT *
FROM product
WHERE product_id NOT IN (SELECT product_id
FROM product2)
- 对称差:并集减去交集
两个集合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)
二、连结
- 内连结–inner join
使用某种关联条件, 将其他表中的列添加过来,进行“添加列”的集合运算
A inner join B on ‘条件’
select *
from table1 join table2 on table1.name = table2.name
- 多表连结
就是连结3张及3张以上的表
select *
from table1 inner join table2 on table1.name=table2.name inner
join table3 on table1.name=table3.name
where name='zs'
- 外连结—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)>