SQL 集合的并、交、差-union、instersect、except

并运算 union

  • 例1: 显示城市在“北京”和(或者)工资大于2000的仓库号
select 城市 from 仓库 where 城市='北京'
union
select 工资 from 职工 where 工资>2000

tip:城市在北京的仓库号:wh1,wh2;工资大于2000的仓库号:wh3,所以并集为wh1,wh2,wh3

利用多表连接方法:

select distinct 仓库.仓库号 from 仓库,职工
    where 仓库.仓库号=职工.仓库号
    and (城市='北京' or 工资>2000)

利用嵌套子查询:

select 仓库号 from 仓库 where 城市='北京'
    or 仓库号 in (select 仓库号 from 职工 where 工资>2000)
  • 例2:显示仓库号,利用集合运算,合并面积和工资,并排序
select 仓库号,面积 as 面积和工资 from 仓库 where 城市='北京'
union
select 仓库号,工资 as 面积和工资 from 职工 where 工资>2000
order by 仓库号 asc
保留重复行 union all

同 union 例一

交集运算 instersect

方法同并union

差运算 except

方法同并union
例如:
北京仓库号:wh1,wh4
工资>2k仓库号:wh1,wh2,wh3
则差集为wh4
嵌套子查询为:

select 仓库号 from 仓库 where 城市='北京'
    and 仓库号 NOT IN(select 工资 from 职工 where 工资>2000)

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/81806232
今日推荐