贴主自学用的SQL Server视频教程,以下是一些笔记:
一、select:查询表记录
1、查询整张表的数据
查询带有某个字段的行数据:Select 字段 From 表名称
查询该表的全部数据:Selcet * from 某表
2、查询中常用distinct(去重)
selcet distinct 想要去重出现的字段//去掉某个字段中重复出现的数据
from 表名//从某个表中查找
例:selcet distinct code from [dbo].[P]//查询P表中的code字段并且去重
3、Top:查询表中的前多少行数据
select Top 行数(int型) 字段名//查询这个表中的带有某个字段的前x行数据
from 表名
例:selcet top 100* from [dbo].[P]//从P表中查找前100行的所有数据
4、where:条件限制
1、精确限制条件
where 字段 = 值
例:
select *from[dbo].[P]
where pno = 1//查找出P表中字段pno=1的所有数据
update [dbo].[P] set pno = 1,where Sno = 3//修改P表中sno为3的行的pno字段为1
2、模糊限制条件
where 字段 like ‘%管理员’
//查询出 管理员前面有其他字段的所有行数据,查出来的数据是:xx管理员
where 字段 like ‘管理员%’
//查询出 管理员后面带有其他字段所有行数据,查出来的数据是:管理员xx
where 字段 like ‘管理员%’
//查询出 管理前面和后面带有其他字段的所有行数据,查出来的数据是:xx管理员xx
3、between语法
1、between数字之间
select * from 表名
where RoleID not between 300 and 399;
//查询RoleID不在300-399之间的数据
2、between字符串之间
5、子查询in
1、IN的运用
select * from 表名
where 字段 in (想要查询的字段值,每个数据用逗号隔开)
2、字查询中in与not in
in
not in
6、子查询exist
1、as的用法:
selcet 表名.字段名 from 表名//用于查询表中带有某个字段的数据
为了方便可以把表名在这个查询当中自定义(as,as可省略)为xxx,相当于给这张表取小名,这样的好处是想查询某个字段的时候直接可以把表名用小名.字段名替代
2、子查询:判断b表的数据在a表中存不存在,存在返回,不存在不返回
主查询:如果子查询成立 查询a表中的a.studentNo,a.studentName,a.Age,a.Sex
select a.studentNo,a.studentName,a.Age,a.Sex from 表名
where exist (select *from 表名 b where a.studentNo = b.studentNo)
//判断b表中的数据是否在a表中存在
7、返回记录排序order by
select * from 表名
order by 字段1名,字段2名,字段3名
(可以一直往后添加想进行排序的字段名,执行的时候先排序前面的字段)
//依次按照字段的数据从小到大排序,默认升序排列asc,在字段名后加desc即可降序排列
降序(从大到小排列)
8、关联查询
1、inner join交叉关联
select * from 表1
inner join 表2
on 表1.字段号 = 表2.字段号
//把表1和表2都当成主表,返回on后的表1表2满足的关联数据,
把两个表相同的字段都返回,其他不满足的不返回
2、left join左关联
select * from 表1
left join 表2
on 表1.字段号 = 表2.字段号
//以表1为主表,返回的是表1的全部数据和满足on条件的表2数据,不满足条件的返回null
3、right join右关联
select * from 表1
right join 表2
on 表1.字段号 = 表2.字段号
//以表2为主表,返回的是表2的全部数据和满足on条件的表1数据,不满足条件的表1数据返回null
4、多表的交叉关联
selcet * from students
select * from lessons
select * from student_lesson
select a.studentsNO,a.studentName,c.lessonNo,c.lessonName
from students a//把students表命名成a表
inner join student_lesson b //a、b都是主表
on a.studentNo = b.studentNo//返回a、b表中同时满足的行数据
inner join lessons c
on b.lessonNo = c.lessonNo//on后面都是表与表之间的关联字段
where a.studentNo = 216 //还可以用where精确查询出你想要的某个数据
通过上一步可以查询到多个表的关联数据,但是会有重复的字段(关联字段)出现,可以对语句进行优化让查询结果只出现自己想要的查的数据:
二、update:修改表记录
1、修改整张表的记录
单表基本操作:(如果不加where会修改整张表的所有数据)如下图:
update 表名
set 字段 = 值
2、只修改某一行的数据:
在1的基础上加上where精确修改某一行的数据:
update 表名
set 字段 = 值
where 字段 = 值
三、删除表记录:
1、删整张表:
delete from 表名
2、精确删除某一行数据:
delete from 表名
where 字段= xx(要不要加单引号取决于字段的数据类型)