SQL Server数据库(高级查询)

时间:2023-03-10 06:21:28
SQL Server数据库(高级查询)

高级查询

1、连接查询

有外键关系的两张表,通过关系一次查询两张表

(1)select * from 表名,表名 --- 直接使用出现笛卡尔积,两个表数据一一对应,查询出的结果数目是两个表的行的乘积,使用连接查询会占用一定的资源

select * from 表名,表名 where 条件

例子:
select * from Info,Nation where Info.Nation =Nation.Code

select Info.Code,Info.Name,Sex,Nation.Name,Birthday from Info,Nation where Info.Nation =Nation.Code

(2)select * from 表名 join 表名 on 条件 --join on 查询

2、联合查询

select code,name from Info
union
select code,name from Nation

注意:联合查询列应当相同,放在一起显示

SQL Server数据库(高级查询)

SQL Server数据库(高级查询)
3、子查询

一条SQL查询中包含两条查询,一个是父查询(外层查询),另一个是子查询(里层查询),子查询的查询的结果作为父查询的条件,可以嵌套多层

--查询民族为汉族的人员信息
select * from Info where Nation =(select code from Nation where Name='汉族')

(1)无关子查询
子查询可以单独执行,子查询和父查询之间不存在一定的关系

--查询系列是宝马5系的所有汽车信息
select * from Car where Brand=( select Brand_code from Brand where Brand_Name='宝马5系')

SQL Server数据库(高级查询)

SQL Server数据库(高级查询)

(2)相关子查询

--查询油耗低于该系列平均油耗的汽车

select * from Car where Oil<(该系列平均油耗)
select avg(Oil) from Car where Brand =(该系列)

select * from Car a where Oil<(select avg(Oil) from Car b where b.Brand =a.Brand)

SQL Server数据库(高级查询)