连接查询1
- 查询数据时,当需要将多个表中的列共同显示到一个结果集中的时候,可以使用连接查询。基于笛卡尔积中相等时。
原表
select
*
from TblPhoneNum inner join TblPhoneType on TblPhoneNum.pTypeld=TblPhoneType.ptID
- 查询部分列时,若两个表的列名相同时应该通过 表名.列名 的方式来限定指定的列时哪张表中的
--查询部分列时,若两个表的列名相同时应该通过 表名.列名 的方式来限定指定的列时哪张表中的
select
pn.pId,
pn.pName,
pn.pCellPhone,
pt.ptName
from TblPhoneNum as pn inner join TblPhoneType as pt on pn.pTypeld=pt.ptID --表名太长时可以起别名
case 查询
原表
--相当于c#中的if-else,可以判断大于等于的范围
--要求then后面的数据类型必须一致
select
*,
头衔=case
when ULevel=1 then '菜鸟'
when ULevel=2 then '大神'
when ULevel=3 then '大师'
else '骨灰级大师'
end
from TblLevel
--相当于c#中的switch,只能是等值判断,不能判断大于等于的范围
select
*,
头衔=case ULevel
when 1 then '菜鸟'
when 2 then '大神'
when 3 then '大师'
else '骨灰级大师'
end
from TblLevel
case查询的练习
- 成绩等级
select
Id,
Name,
English,
等级=case
when 95<=English then '优'
when 80<=English then '良'--若第一个满足则不执行第二个判断,所以不用限制小于
when 70<=English then '中'
else '差'
end
from TblScore
select * from TblTestA
select
*,
是否及格=case
when English>=60 and Math>=60 then '及格'
else '不及格'
end
from TblScore
- A,B,C比较
select
x=case
when A>B then A
else B
end,
y=case
when B>C then B
else C
end
from TblTestA
- 显示收入支出
select
单号=number,
收入=case
when amount>=0 then amount
else 0
end,
支出=case
when amount<=0 then -1*amount --或者可以使用abs()求绝对值
else 0
end
from TblTestB
- 比赛胜负统计
select
团队=teamName,
胜=sum(case
when gameResult='胜' then 1
else 0
end),
负=sum(case
when gameResult='负' then 1
else 0
end)
from TblTeamScore
group by teamName
---count不统计空值
select
团队=teamName,
胜=count(case
when gameResult='胜' then '胜'
else NULL
end),
负=count(case
when gameResult='负' then '负'
else NULL
end)
from TblTeamScore
group by teamName
- NBA得分排名
select
teamName,
第1赛季得分=max(case
when seasonName='第1赛季' then Score
else NULL
end),
第2赛季得分=max(case
when seasonName='第2赛季' then Score
else NULL
end),
第3赛季得分=max(case
when seasonName='第3赛季' then Score
else NULL
end)
from TblNBAScore
group by teamName
索引
- 索引演示
- 打开统计信息:查询—查询选项—高级—set statistics time,set statistic io
- 打开“实际的执行计划”
创建聚集索引的语句creat clustered index 索引名 on 表名
创建非聚集索引语句creat nonclustered index 索引名on 表名
删除索引的语句drop index 表名.索引名
当模糊查询的时候 最好将%放在后面才会用到索引,比如
where column like 'aa%'
子查询
- 独立子查询
select * from TblStudent where ClassId