sql 完全/交叉/自连接

2021-06-25  本文已影响0人  Vergil_wj

完全连接 full join

select productStocks.*,orderform.*
    from productStocks
    full join  orderform
    on productStocks.pID = orderfor.pID

结果集包含三部分内容:

  1. 两个表中匹配所有行记录。
  2. 左表中那些在右表中找不到匹配的行的记录,这些记录的右边全为 null。
  3. 右表中那些在左表中找不到匹配的行的记录,这些记录的左边全为 null。

交叉连接 cross join

select * from emp cross join dept 

等价于

select * from emp,dept

自连接

一张表自己和自己连接起来查询数据

例:不使用聚合函数,求出薪水最高的员工

使用聚合函数:

select *
    from emp
    where sal = (select max(sal) from emp)

不使用聚合函数,自连接:

select * 
    from emp
    where empo not in(
                          select distinct "E1".empno
                          from emp "E1"
                          join emp "E2"
                          on "E1".sal < "E2".sal  -- 只有 "E1" 表的最高工资不在结果集中
                      )
上一篇 下一篇

猜你喜欢

热点阅读