【数据库】集合运算UNION,INTERSECT,EXCEPT,JOIN

本文介绍了SQL中集合运算的概念,包括UNION(求并集)、INTERSECT(求交集)和EXCEPT(求差集),详细讲解了它们的使用规则和注意事项。此外,还探讨了JOIN操作,如内连接、外连接以及如何通过JOIN创建新表。通过示例和练习帮助理解这些概念。
摘要由CSDN通过智能技术生成

7.1 表的加减法
7.3 表之间的加法运算UNION(求并集)

postgres=# SELECT product_id,product_name
postgres-# FROM Product
postgres-# UNION
postgres-# SELECT product_id,product_name
postgres-# FROM Product2;
 product_id | product_name
------------+--------------
 0001       | T恤
 0009       | 手套
 0004       | 菜刀
 0002       | 打孔器
 0010       | 水壶
 0006       | 叉子
 0005       | 高压锅
 0007       | 擦菜板
 0003       | 运动T恤
 0008       | 圆珠笔
(10 行记录)

注:1.自动去除重复记录 2.列数和数据类型保持一致 3.SELECT语句可以无限使用,ORDER BY语句只能在最后使用一次。
7.5 保留重复行

postgres=# SELECT product_id,product_name
postgres-# FROM Product
postgres-# UNION ALL
postgres-# SELECT product_id ,product_name
postgres-# FROM Product2
postgres-# ;
 product_id | product_name
------------+--------------
 0001       | T恤
 0002       | 打孔器
 0003       | 运动T恤
 0004       | 菜刀
 0005       | 高压锅
 0006       | 叉子
 0007       | 擦菜板
 0008       | 圆珠笔
 0001       | T恤
 0002       | 打孔器
 0003       | 运动T恤
 0009       | 手套
 0010       | 水壶
(13 行记录)

7.6 选取两个表中的公共部分INTERSECT(交集)

postgres=# SELECT product_id,product_name
postgres-# FROM Product
postgres-# INTERSECT
postgres-# SELECT product_id,product_name
postgres-# FROM Product2;
 product_id | product_name
------------+--------------
 0001       | T恤
 0002       | 打孔器
 0003       | 运动T恤
(3 行记录)

7.7 对记录做减法运算EXCEPT

postgres=# SELECT product_id,product_name
postgres-# FROM Product
postgres-# EXCEPT
postgres-# SELECT product_id,product_name
postgres-# FROM Product2;
 product_id | product_name
------------+--------------
 0006       | 叉子
 0004       | 菜刀
 0005       | 高压锅
 0007       | 擦菜板
 0008       | 圆珠笔
(5 行记录)

示意图:
在这里插入图片描述
注:语句的顺序会影响结果
7.2 连结JOIN(列会改变)
7.8 将两张表进行内连接

postgres=# SELECT SP.shop_id,SP.shop_name,SP.product_id,P.product_name,
postgres-# P.sale_price
postgres-# FROM ShopProduct AS SP INNER JOIN Product AS P
postgres-# ON SP.product_id=P.product_id;
 shop_id | shop_name | product_id | product_name | sale_price
---------+-----------+------------+--------------+------------
 000D    | 福冈      | 0001       | T恤          |       1000
 000A    | 东京      | 0001       | T恤          |       1000
 000B    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值