数据库-T-SQL 语句-高级查询

1.连接查询(对列的扩展,把两张表连接到一起显示)(数据量大时少用此类查询,速度慢,会形成笛卡尔积)

第一种形式

select * from Info,Nation  #会笛卡尔积

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 #查询指定列 ,如果两个表有相同列名,需要加上表名 如 Info.Code,如果不重名,可以直接写列名

select Info.Code as '代号',Info.Name as '姓名',Sex as '性别',Nation.Name as '民族',Birthday as '生日' from Info,Nation where Info.Nation = Nation.Code  #改表头 在列名后面 用  as ''改表头

第二种形式:

select * from Info join Nation  #会形成笛卡尔积

select * from Info join Nation on Info.Nation = Nation.Code # join on  on后面加筛选条件  

2.联合查询(对行的扩展)

select * from Info where Nation = 'n002'

union

select * from Info where Code = 'p002'

3.子查询:在一个SQL语句中,至少有两个查询,其中一个A查询的结果作为另一个B的查询条件 A称为里层查询或者子查询,B称为外层查询或父查询

3.1无关子查询

无关子查询特点:子查询可以单独执行

查询民族为“汉族的“人员信息

select * from Info where Nation = (select Code from Nation where Name = '汉族')

select * from Info where Nation in (select Code from Nation where Name = '汉族' or Name ='回族')  #结果不止一条时 用 in 连接 。 not in 不在查询结果里的  与  in 相反。

3.2相关子查询

查询同一系列的油耗比平均油耗低的汽车信息

select avg(Oil) from Car where Brand =''

select * from Car where Oil < 平均油耗

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

原文地址:https://www.cnblogs.com/yifangtongxing/p/5329736.html