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