SQL 多表连接查询

不连接的多表的错误查询会显示笛卡儿积个记录

简单多表连接

  • 例1:显示职工表中的姓名和工资,仓库表中的城市,职工表和仓库表用仓库号连接
select 姓名,工资,城市 from 职工,仓库 where 职工.仓库号=仓库.仓库号
  • 例2:显示职工的姓名、工资及城市,条件:工资1500~2000,城市:北京
use db_name
go
select 姓名,工资,城市 from 职工,仓库 where 职工.仓库号=仓库.仓库号
    and (工资 between 1500 and 2000) and 城市='北京'
  • 例3:显示职工的姓名、工资及城市,条件:工资不在1500~2000,城为空
select 姓名,工资,城市 from 职工,仓库 where 职工.仓库号=仓库.仓库号
    and not(工资 between 1500 and 2000) and 城市 is null

复杂多表连接

  • 例:显示职工的姓名、工资、销售金额,条件:工资大于不同仓库的平均工资的最大值
select 姓名,工资,金额 from 职工,订单 where 职工.订单号=订单.订单号
    and 工资>ALL(select avg(工资) from 职工 GROUP BY 仓库号)

保存新表 into

  • 例:利用SQL生产一张新表,表中字段是仓库号、城市、姓名/工资、销售额
select 仓库号,城市,姓名,工资,金额 INTO new_table_name 
    from 职工,仓库,订单 
    where 职工.仓库号=仓库.仓库号 and 职工.订单号=订单.订单号

查看新表new_table_name

select * from new_table_name

查看不同仓库所有职工的仓库号,平均销售额

select 仓库号,avg(金额) as 平均销售额 from new_table_name group by 仓库号

tip:原有的多个表是无法实现分组查询功能的,只能在新表中实现

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/81457662