多表联结查询:
内联(inner join)
select
from 表1
inner join 表2
on 联结条件
where 筛选条件
select
from 表1,表2
where 联结条件 and 筛选条件
外联(left/right/full join)有方向性
左边联结 left join 左边的表不加限制,以左表为主
select *
from stu as a
left join sc as b
on a.sid=b.sid
右边联结 right join 右边的表不加限制,以右表为主
select *
from stu as a
right join sc as b
on a.sid=b.sid
全外(full join) 左右两表都不加限制
select *
from stu as a
full join sc as b
on a.sid=b.sid
交叉联结 (cross join)
select *
from stu
full join sc
子查询:在一个SQL语句中包含另一个查询语句,可以用于增删改查任何操作,子查询通常用于提供值作为筛选条件,或者查入的数据来使用。通常用in代替=,用not in代替!=
select···from表1 where 字段1>(子查询)
select *
from 学员信息
where stuno in
(select stuno
from 成绩表
where writtenexam=60)
视图
View:表数据的映射
Create View 视图名
As
(
查询语句
)
视图的更新删除只能针对来源一张表的数据,不能来源于多个表。
索引
Index:提高查询效率
Create [Unique] Index 索引名
On 表名(字段名)
Case 字段名
Case 字段名
When 值 then 显示值
When 值 then 显示值
...
[Else 显示值]
End
select
case sname
When 'aaa' then '张三'
When 'bbb' then '李四'
[Else sname]
End
from stu
行转列
pivot(max(行值字段) for 行转列字段 in (新列字段名)) as 别名
pivot(max(score) for cid in ([1],[2],[3])) as a
列转行
unpivot(行值字段名 for 列转行字段 in (列名)) as 别名
unpivot(score for cid in ([1],[2],[3])) as b