侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Mysql基础知识点汇总

数据库  /  管理员 发布于 6年前   209

1.什么是SQL语句

sql语言:结构化的查询语言。(Structured Query Language),是关系数据库管理系统的标准语言。

它是一种解释语言:写一句执行一句,不需要整体编译执行。

语法特点:

1.没有“ ”,字符串使用‘ '包含
2.没有逻辑相等,赋值和逻辑相等都是=
3.类型不再是最严格的。任何数据都可以包含在‘ '以内
4.没有bool值的概念,但是在视图中可以输入true/false
5.它也有关系运算符:> < >= <= = <> != ,它返回一个bool值
6.它也有逻辑运算符: !(not) &&(and) ||(or)
7.它不区别大小写

2.使用sql语句创建数据库和表

语法:

create database 数据库名称on primary --默认在主文件组上(name='逻辑名称_data' , --当你发现它不是一句完整的sql语句,而仅仅是一个处理结构中的某一句的时候,就需要添加 ,size=初始大小,--数值不包含在‘'以内filegrowth=文件增长 ,maxsize=最大容量,filename='物理路径')log on(name='逻辑名称_log' , --当你发现它不是一句完整的sql语句,而仅仅是一个处理结构中的某一句的时候,就需要添加 ,size=初始大小,--数值不包含在‘'以内filegrowth=文件增长 ,maxsize=最大容量, --一般来说日志文件不限制最大容量filename='物理路径')


--判断数据库文件是否已经存在 :数据库的记录都存储在master库中的sysdatabases表中
--自动切换当前数据库
--使用代码开启外围应该配置器

exec sp_configure 'show advanced options' ,1RECONFIGUREexec sp_configure 'xp_cmdshell',1RECONFIGURE

--自定义目录  xp_cmdshell可以创建出目录   'mkdir f:\project':指定创建目录
exec xp_cmdshell 'mkdir f:\project'

use master
--exists 函数判断()中的查询语句是否返回结果集,如果返回了结果集则得到true,否则得到false

if exists( select * from sysdatabases where name='School')  drop database School --删除当前指定名称的数据库create database Schoolon primary( name='School_data',--逻辑名称.说明最多能够存储100mb数据,如果没有限制就可以将硬盘存储满 size=3mb,--初始大小 maxsize=100mb,--最大容量 filegrowth=10%,--文件增长一次增长10% filename='f:\project\School_data.mdf'  ),

--创建文件组

filegroup mygroup( name='School_data1',--逻辑名称.说明最多能够存储100mb数据,如果没有限制就可以将硬盘存储满 size=3mb,--初始大小 maxsize=100mb,--最大容量 filegrowth=10%,--文件增长一次增长10% filename='F:\qiyi\School_data1.ndf'  )log on( name='School_log',--逻辑名称 size=3mb,--初始大小 --maxsize=100mb,--最大容量 filegrowth=10%,--文件增长一次增长10% filename='f:\project\School_log.ldf'  ),( name='School_log1',--逻辑名称 size=3mb,--初始大小 --maxsize=100mb,--最大容量 filegrowth=10%,--文件增长一次增长10% filename='F:\qiyi\School_log1.ldf'  )

3.创建数据表

语法:

create table 表名
(
字段名称 字段类型 字段特征(是否为null,默认值 标识列 主键 唯一键 外键 check约束),
字段名称 字段类型 字段特征(是否为null,默认值 标识列 主键 唯一键 外键 check约束)
)
创建老师表Teacher :Id、Name、Gender、Age、Salary、Birthday

use Schoolif exists(select * from sysobjects where name='Classes') drop table Classescreate table Classes( Classid int identity(1,1), ClassName nvarchar(50) not null )if exists(select * from sysobjects where name='teacher') drop table teachercreate table Teacher( Id int identity(1,1),--可以同时创建多个特征,用空格 分隔开。 identity是标识列,第一个参数是种子,第二个是增量Name nvarchar(50) not null,-- not null标记它的值不能为null--不能不填写ClassId int not null, Gender bit not null,Age int  ,Salary money, --如果不标记为 not null.那么就相当于标记了nullBirthday datetime )

4.数据完整性约束

实体完整性:实体就是指一条记录。这种完整性就是为了保证每一条记录不是重复记录。是有意义的

主键:非空和唯一.一个表只有一个主键,但是一个主键可以是由多个字段组成的 组合键
标识列:系统自动生成,永远不重复
唯一键:唯一,但是可以为null,只能null一次
域完整性:域就是指字段,它是为了保证字段的值是准和有效,合理值

类型 是否null,默认值,check约束,关系
自定义完整性:

check约束 , 存储过程 触发器
引用完整性:一个表的某个字段的值是引用自另外一个表的某个字段的值。引用的表就是外键表,被引用的表就是主键表

1.建立引用的字段类型必须一致
2.建立引用的字段的意义一样
3.建立主外键关系的时候选择 外键表 去建立主外键关系
4.建立主外键关系的字段在主表中必须是主键或者唯一键

5.对于操作的影响

①.在添加数据时,先添加主键表再添加外键表数据
②.在删除的时候先外键表数据再删除主键表数据

级联的操作:不建议使用:会破坏数据完整性
不执行任何操作:该报错就报错,该删除就删除
级联:删除主表记录,从表引用该值的记录也被删除
设置null:删除主表记录,从表对应的字段值设置为null,前提是可以为null
设置为default:删除主表记录,从表对应的字段值设置为default,前提是可以为default
主键约束(PK Primary key)唯一键约束(UQ unique) 外键约束(FK foreign key) 默认值约束(DF default) check约束(CK check)

语法:

alter table 表名
add constraint 前缀_约束名称 约束类型 约束说明(字段 关系表达式 值)
use School
if exists(select * from sysobjects where name='PK_Classes_Classid')
 alter table classes  drop constraint PK_Classes_Classid
alter table classes
add constraint PK_Classes_Classid primary key(classid)
--为id添加主键
alter table teacher
add constraint PK_teacher_id primary key(id)
--为name添加唯一键
alter table teacher
add constraint UQ_Teacher_Name unique(Name)
--同时创建salary的默认约束和age的check约束
alter table teacher
add constraint DF_Teacher_Salary default(5000) for salary,
constraint CK_Teacher_Age check(age>0 and age<=100)
--为teacher表的classid字段创建主外键
if exists(select * from sysobjects where name='FK_Teacher_Classes_Classid')
 alter table teacher  drop constraint FK_Teacher_Classes_Classid
alter table teacher
with nocheck --不检查现有数据
add constraint FK_Teacher_Classes_Classid foreign key(classid) references classes(classid)
--on delete set default  级联操作
--不执行任何操作:该报错就报错,该删除就删除  --no action --默认选择
--级联:删除主表记录,从表引用该值的记录也被删除 --cascade
--设置null:删除主表记录,从表对应的字段值设置为null,前提是可以为null   --set null
--设置为default:删除主表记录,从表对应的字段值设置为default,前提是可以为default  --set default

5.四中基本字符类型说明

--len(参数) --获取指定参数内容的字符个数
select LEN('abcd') 【4】运行结果
select LEN('中华人民共和国') 【7】

--DataLength(参数):获取指定内占据的字节数--空间大小
select DataLength('abcd') 【4】
select DataLength('中华人民共和国') 【14】

--char类型:当空间分配后,不会因为存储的内容比分配的空间小就回收分配的空间。但是如果存储的内容超出了指定的空间大小,就会报错,当你存储的内容的长度变化区间不大的时候可以考虑使用char
select LEN(char) from CharTest 【2】
select DataLength(char) from CharTest 【10】

--varchar  var--变化的:当你存储的内容小于分配的空间的时候,多余的空间会自动收缩。但是如果存储的内容超出了指定的空间大小,就会报错 当存储的内容波动区间比较大时候使用varchar
select LEN(varchar) from CharTest 【2】
select DataLength(varchar) from CharTest 【2】

--nchar--  n代表它是一个unicode字符。规定不管什么样的字符都占据两个字节。  char:空间是固定的
select LEN(nchar) from CharTest 【10】
select DataLength(nchar) from CharTest 【20】

--nvarchar  n  var  char
select LEN(nvarchar) from CharTest 【2】
select DataLength(nvarchar) from CharTest 【4】

6.SQL基本语句

数据插入

调用方法 一 一对应原则:类型对应,数量对应,顺序对应。

语法: 形参 实参

insert into 表名([字段列表]) values(值列表) --数据必须要符合数据完整性
插入操作是单个表的操作
插入操作insert一次只能插入一条记录
use School
--插入teacher所有字段的数据.如果在表后没有指定需要插入的字段名称,那么就默认为所有字段添加值
--但是一定需要注意的是:标识列永远不能自定义值--不能人为插入值
--仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表'Teacher'中的标识列指定显式值。
insert into Teacher values('张三',5,1,30,4000,'1984-9-11')
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('张三',5,1,30,4000,'1984-9-11')
--不为可以为null的字段插入值  :可以null的字段可以不赋值
--列名或所提供值的数目与表定义不匹配
insert into Teacher(Name,ClassId,Gender,Age,Salary) values('李四',5,1,30,4000)
--非空字段一定需要赋值 :不能将值 NULL 插入列 'Gender',表 'School.dbo.Teacher';列不允许有 Null 值。INSERT 失败
insert into Teacher(Name,ClassId,Age,Salary) values('李四',5,30,4000)
--为有默认值的字段插入值:
--1.不写这一列让系统自动赋值
insert into Teacher(Name,ClassId,Gender,Age) values('王五',5,1,30)
--指定 null或者default
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('赵六',5,1,30,default,null)
--数据必须完全符合表的完整性约束
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('赵六1',5,1,300,default,null)

--任意类型的数据都可以包含在''以内,     不包括关键字
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('马鹏飞','5','0','15',default,null)
--但是字符串值如果没有包含在''以内.会报错   列名 '兰鹏' 无效。
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('兰鹏','5','0','15',default,null)
--但是数值组成的字符串可以不使用''包含
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values(123,'5','0','15',default,null)
--日期值必须包含在'‘以内,否则就是默认值
insert into Teacher(Name,ClassId,Gender,Age,Salary,Birthday) values('邹元标2','5','0','15',default,'1991-9-11')
数据删除

语法:

delete [from] 表名 where 条件
delete from Teacher where Age<20
--特点:
--1.删除是一条一条进行删除的
--2.每一条记录的删除都需要将操作写入到日志文件中
--3.标识列不会从种子值重新计算,以从上次最后一条标识列值往下计算
--4.这种删除可以触发delete触发器

--truncate table 表名 --没有条件,它是一次性删除所有数据
--特点:
--1.一次性删除所有数据,没有条件,那么日志文件只以最小化的数据写入
--2.它可以使用标识列从种子值重新计算
--3.它不能触发delete触发器
truncate table teacher
数据更新(数据修改):一定需要考虑是否有条件

语法:

update 表名 set 字段=值,字段=值 。。where 条件
update Teacher set Gender='true'
--修改时添加条件
update Teacher set Gender=0 where Id=20
--多字段修改
update Teacher set ClassId=4,Age+=5,Salary=5000 where Id=22
--修改班级id=4,同时年龄》20岁的人员工资+500
update Teacher set Salary=Salary+500 where ClassId=4 and Age>20
数据检索--查询

语法: *代表所有字段

select */字段名称列表 from 表列表
select StudentNo,StudentName,Sex,[Address] from Student
--可以为标题设置  别名,别名可以是中文别名
select StudentNo as 学号,StudentName 姓名,性别=Sex,[Address] from Student
--添加常量列
select StudentNo as 学号,StudentName 姓名,性别=Sex,[Address] ,国籍='中华人民共和国' from Student
--select的作用
--1.查询
--2.输出
select 1+1
--+是运算符,系统会自动为你做类型转换
select 1+'1'
select '1'+1
--如果+两边都是字符串,那么它就是一字符串连接符
select '1'+'1'
select 'a'+1
--可以输出多列值
select 1,2,34,3,545,67,567,6,7
--Top、Distinct
select * from Student
--top可以获取指定的记录数,值可以大于总记录数.但是不能是负值
select top 100 * from Student
--百分比是取ceiling()
select top 10 percent * from Student

--重复记录与原始的数据表数据无关,只与你查询的结果集有关系 distinct可以去除结果集中的重复记录--结果集中每一列的值都一样
select distinct LoginPwd,Sex,Email from Student
select distinct Sex from Student

select的作用
--聚合函数:
--1.对null过滤
--2.都需要有一个参数
--3.都是返回一个数值
--sum():求和:只能对数值而言,对字符串和日期无效
--avg():求平均值
--count():计数:得到满足条件的记录数
--max():求最大值:可以对任意类型的数据进行聚合,如果是字符串就比较拼音字母进行排序
--min():求最小值
--获取学员总人数
select COUNT(*) from Student
--查询最大年龄值
select  MIN(BornDate) from Student
select  max(BornDate) from Student

--查询总分
select SUM(StudentResult) from Result where StudentNo=2
--平均分
select avg(StudentResult) from Result where SubjectId=1
--注意细节:
select  SUM(StudentName) from Student
select  SUM(BornDate) from Student

select  min(StudentName) from Student
select  max(StudentName) from Student

--查询学号,姓名,性别,年龄,电话,地址 ---查询女生
select StudentNo,StudentName,Sex,BornDate,Address from Student where Sex='女' and BornDate >'1990-1-1' and Address='广州传智播客'
--指定区间范围
select StudentNo,StudentName,Sex,BornDate,Address from Student where  BornDate >='1990-1-1' and BornDate<='1993-1-1'
--between...and  >=  <=
select StudentNo,StudentName,Sex,BornDate,Address from Student where BornDate  between '1990-1-1' and '1993-1-1'
--查询班级id  1  3 5  7的学员信息
select * from Student where ClassId=1 or ClassId=3 or ClassId=5 or ClassId=7
--指定具体的取值范围--可以是任意类型的范围.值的类型需要一致--可以相互转换
select * from Student where ClassId in(1,3,'5',7)
select * from Student where ClassId not in(1,3,'5',7)

聚合函数
--带条件的查询-模糊查询-- 只针对字符串而言

--查询  姓 林 的女生信息
--=是一种精确查询,需要完全匹配
select * from Student where Sex='女' and StudentName='林'
--通配符--元字符
--%:任意个任意字段  window:*  正则表达式 :.*
--_:任意的单个字符
--[]:代表一个指定的范围,范围可以是连续也可以是间断的。与正则表达式完全一样[0-9a-zA-Z].可以从这个范围中取一个字符
--[^]:取反值
select * from Student where Sex='女' and StudentName='林%'
--通配符必须在模糊查询关键的中才可以做为通配符使用,否则就是普通字符
--like   像 。。。。一样
select * from Student where Sex='女' and StudentName  like '林%'
select * from Student where Sex='女' and StudentName  like '林_'
--[]的使用  学号在11~15之间的学员信息
select * from Student where StudentNo like '[13579]'

---处理null值
--null:不是地址没有分配,而是不知道你需要存储什么值  所以null是指   不知道。但是=只能匹配具体的值,而null根本就不是一个值
select COUNT(email) from Student where Email !=null
select COUNT(email) from Student where Email  is null
select count(email) from Student where Email  is not null
--将null值替换为指定的字符串值
select StudentName,ISNULL(Email,'没有填写电子邮箱') from Student where ClassId=2

模糊查询
--当你看到  每一个,,各自,不同,,分别  需要考虑分组
--查询每一个班级的男生人数
--与聚合函数一起出现在查询中的列,要么也被聚合,要么被分组
select classid,Sex,COUNT(*) from Student where Sex='男' group by ClassId,sex
--查询每一个班级的总人数,显示人数>=2的信息
--1.聚合不应出现在 WHERE 子句中--语法错误
select ClassId ,COUNT(*) as num from Student where Email is not null   GROUP by ClassId having COUNT(*)>=2 order by num desc
--完整的sql查询家庭
 --5                            1                      2                                 3                                     4                                           6                                                
--select 字段列表 from 表列表  where 数据源做筛选 group by 分组字段列表 having 分组结果集做筛选 Order by  对结果集做记录重排

select ClassId ,COUNT(*) as num from Student where Email is not null   GROUP by ClassId order by ClassId desc

--关于top的执行顺序 排序之后再取top值
select top 1 ClassId ,COUNT(*) as num from Student  GROUP by ClassId  order by num desc

分组统计

7.类型转换函数

--select :输出为结果集--虚拟表
--print:以文本形式输出  只能输出一个字符串值.

print 1+'a'
select 1,2

select * from Student

--类型转换
--Convert(目标类型,源数据,[格式]) --日期有格式
print '我的成绩是:'+convert(char(3),100)

print '今天是个大日子:'+convert(varchar(30),getdate(),120)
select getdate()
select len(getdate())

--cast(源数据  as  目标类型)  它没有格式
print '我的成绩是:'+cast(100 as char(3))

8.日期函数

--getdate():获取当前服务器日期
select GETDATE()
--可以在源日期值是追加指定时间间隔的日期数
select DATEADD(dd,-90,GETDATE())
--dateDiff:找到两个日期之间指定格式的差异值
select StudentName,DATEDIFF(yyyy,getdate(),BornDate) as age from Student order by  age
--DATENAME:可以获取日期的指定格式的字符串表现形式
select DATENAME(dw,getdate())
--DATEPART:可以获取指定的日期部分
select cast(DATEPART(yyyy,getdate()) as CHAR(4))+'-' +cast(DATEPART(mm,getdate()) as CHAR(2))+'-' +cast(DATEPART(dd,getdate()) as CHAR(2))

9.数学函数

--rand:随机数:返回0到1之间的数,理论上说可以返回0但是不能返回1
select RAND()
--abs:absolute:取绝对值
select ABS(-100)
--ceiling:获取比当前数大的最小整数
select CEILING(1.00)
--floor:获取比当前数小的最大整数
select floor(1.99999)
power:
select POWER(3,4)
--round():四舍五入.只关注指定位数后一位
select ROUND(1.549,1)
--sign:正数==1  负数 ==-1  0=0
select SIGN(-100)

select ceiling(17*1.0/5)

10.字符串函数

--1.CHARINDEX --IndexOf():能够返回一个字符串在源字符串的起始位置。找不到就返回0,如果可以找到就返回从1开始的索引--没有数组的概念
--第一个参数是指需要查询的字符串,第二个是源字符串,第三个参数是指从源字符的那个索引位置开始查找
select CHARINDEX('人民','中华人民共和国人民',4)
--LEN():可以返回指定字符串的字符个数
select LEN('中华人民共和国')
--UPPER():小写字母转换为大写字母  LOWER():大写转小写
select LOWER(UPPER('sadfasdfa'))
--LTRIM:去除左空格  RTIRM:去除右空格
select lTRIM(RTRIM('                   sdfsd             '))+'a'
--RIGHT:可以从字符串右边开始截取指定位数的字符串  如果数值走出范围,不会报错,只会返回所有字符串值,但是不能是负值
select RIGHT('中华人民共和国',40)
select LEFT('中华人民共和国',2)
--SUBSTRING()
select SUBSTRING('中华人民共和国',3,2)
--REPLACE 第一个参数是源字符串,第二个参数是需要替换的字符串,第三个参数是需要替换为什么
select REPLACE('中华人民共和国','人民','居民')
select REPLACE('中        华      人民       共        和       国',' ','')
--STUFF:将源字符串中从第几个开始,一共几个字符串替换为指定的字符串
select STUFF('中华人民共和国',3,2,'你懂的')

[email protected]

declare @email varchar(50)='[email protected]'
select CHARINDEX('@',@email)
select LEFT(@email,CHARINDEX('@',@email)-1)

--使用right
select right(@email,len(@email)-CHARINDEX('@',@email))
--使用substring
select SUBSTRING(@email,CHARINDEX('@',@email)+1,LEN(@email))
--使用stuff
select STUFF(@email,1,CHARINDEX('@',@email),'')

11.联合结果集union

--联合结果集union
select * from Student where Sex='男'
--union
select * from Student where Sex='女'

--联合的前提是:
--1.列的数量需要一致:使用 UNION、INTERSECT 或 EXCEPT 运算符合并的所有查询必须在其目标列表中有相同数目的表达式
--2.列的类型需要可以相互转换
select StudentName,Sex from Student --在字符串排序的时候,空格是最小的,排列在最前面
union
select cast(ClassId as CHAR(3)),classname from grade

--union和union all的区别
--union是去除重复记录的
--union all不去除重复 :效率更高,因为不需要判断记录是否重复,也没有必须在结果庥是执行去除重复记录的操作。但是可以需要消耗更多的内存存储空间
select * from Student where ClassId=2
union all
select * from Student where ClassId=2

--查询office这科目的全体学员的成绩,同时在最后显示它的平均分,最高分,最低分
select ' '+cast(StudentNo as CHAR(3)),cast(SubjectId as CHAR(2)),StudentResult from Result where SubjectId=1
union
select '1','平均分',AVG(StudentResult) from Result where SubjectId=1
union
select '1','最高分',max(StudentResult) from Result where SubjectId=1
union
select '1','最低分',min(StudentResult) from Result where SubjectId=1

--一次性插入多条数据
--1.先将数据复制到另外一个新表中,删除源数据表,再将新表的数据插入到源数据表中
--1.select */字段  into 新表 from 源表
--1.新表是系统自动生成的,不能人为创建,如果新表名称已经存在就报错
--2.新表的表结构与查询语句所获取的列一致,但是列的属性消失,只保留非空和标识列。其它全部消失,如主键,唯一键,关系,约束,默认值
select * into newGrade from grade

truncate table grade
select *  from newGrade
--select * into grade from newGrade
--2.insert into  目标表  select 字段列表/* from  数据源表
--1、目标表必须先存在,如果没有就报错
--2.查询的数据必须符合目标表的数据完整性
--3.查询的数据列的数量和类型必须的目标的列的数量和对象完全对应
insert into grade select classname from newGrade
delete from admin
--使用union一次性插入多条记录
--insert into 表(字段列表)
--select 值。。。。 用户自定义数据
--union
--select 值 。。。。
insert into Admin
select 'a','a'
union all
select 'a','a'
union all
select 'a','a'
union all
select 'a',null

12.CASE函数用法

相当于switch case---c#中的switch...case只能做等值判断
这可以对字段值或者表达式进行判断,返回一个用户自定义的值,它会生成一个新列。
2.要求then后面数据的类型一致
1.第一种做等值判断的case..end

case 字段或者表达式
when .值..then .自定义值
when .值..then .自定义值
.....
 else 如果不满足上面所有的when就满足这个else
end
--显示具体班级的名称
select StudentNo,StudentName,
case ClassId  --如果case后面接有表达式或者字段,那么这种结构就只能做等值判断,真的相当于switch..case
  when 1 then '一班'
  when 2 then '2班'
  when 3 then '3班'
  when null  then 'aa' --不能判断null值
  else  '搞不清白'
end,
sex
 from Student
--2.做范围判断,相当于if..else,它可以做null值判断
--case  --如果没有表达式或者字段就可实现范围判断
-- when  表达式  then 值   --不要求表达式对同一字段进行判断
-- when  表达式  then 值 
-- .....
--else  其它情况 
--end
select StudentNo,StudentName,
case
 when BornDate>'2000-1-1' then '小屁孩'
 when BornDate>'1990-1-1' then '小青年'
 when BornDate>'1980-1-1' then '青年' 
 --when Sex='女'  then '是女的'
 when BornDate is null then '出生不详'
 else  '中年'
end
 from Student

--百分制转换为素质教育  90 -A   80--B  70 --C  60 --D  <60 E  NULL--没有参加考试
select StudentNo,SubjectId,
case
    when StudentResult>=90 then 'A'
    when StudentResult>=80 then 'B'
    when StudentResult>=70 then 'C'
    when StudentResult>=60 then 'D'
    when StudentResult is null then '没有参加考试'
    else 'E'
end 成绩,
ExamDate
 from Result

13.IF ELSE语法

1.没有{},使用begin..end.如果后面只有一句,可以不使用begin..end包含
2.没有bool值,只能使用关系运算符表达式
3.也可以嵌套和多重
4.if后面的()可以省略

declare @subjectname nvarchar(50)='office' --科目名称
declare @subjectId int=(select Subjectid from Subject where SubjectName=@subjectname) --科目ID
declare @avg int --平均分
set @avg=(select AVG(StudentResult) from Result where SubjectId=@subjectId and StudentResult is not null) --获取平均分
print @avg
if @avg>=60
 begin
   print '成绩不错,输出前三名:'
   select top 3 * from Result where SubjectId=@subjectId order by StudentResult desc
 end
else
  begin
    print '成绩不好,输出后三名:'
    select top 3 * from Result where SubjectId=@subjectId order by StudentResult 
  end

14.WHILE循环语法

1.没有{},使用begin..end
2.没有bool值,需要使用条件表达式
3.可以嵌套
4.也可以使用break,continue

godeclare @subjectName nvarchar(50)='office' --科目名称declare @subjectId int--科目IDdeclare @classid int =(select classid from Subject where SubjectName=@subjectName) --查询当前科目属于那一个班级set @subjectId=(select SubjectId from Subject where SubjectName=@subjectName) --获取科目IDdeclare @totalCount int --总人数 :那一个班级需要考试这一科目 set @totalCount=(select COUNT(*) from Student where ClassId=@classid)print @totalcount --14declare @unpassNum int --不及格人数set @unpassNum=(select COUNT(distinct Studentno) from Result where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<60)while(@unpassNum>@totalCount/2)begin --执行循环加分 update Result set StudentResult+=2 where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<=98 --重新计算不及格人数 set @unpassNum=(select COUNT(distinct Studentno) from Result where SubjectId=@subjectId and StudentNo in(select StudentNo from  Student where ClassId=@classid) and StudentResult<60)endgodeclare @subjectName nvarchar(50)='office' --科目名称declare @subjectId int--科目IDdeclare @classid int =(select classid from Subject where SubjectName=@subjectName) --查询当前科目属于那一个班级set @subjectId=(select SubjectId from Subject where SubjectName=@subjectName) --获取科目IDdeclare @totalCount int --总人数set @totalCount=(select COUNT(*) from Student where ClassId=@classid)print @totalcount --14declare @unpassNum int --不及格人数while(1=1) begin   set @unpassNum=(select COUNT(distinct Studentno) from Result where SubjectId=@subjectId and StudentNo in(select StudentNo  from  Student where ClassId=@classid) and StudentResult<60)  if(@unpassNum>@totalCount/2)       update Result set StudentResult+=2 where SubjectId=@subjectId and StudentNo in(select StudentNo from Student where ClassId=@classid) and StudentResult<=98  else     break end

15.子查询

子查询:一个查询中包含另外一个查询。被包含的查询就称为子查询,包含它的查询就称父查询。
1.子查询的使用方式:使用()包含子查询
2.子查询分类:

独立子查询:子查询可以直接独立运行.
查询比“王八”年龄大的学员信息
select * from Student where BornDate<(select BornDate from Student where StudentName='王八')
相关子查询:子查询使用了父查询中的结果
--子查询的三种使用方式
--1.子查询做为条件,子查询接在关系运算符后面  >  < >= <= = <> !=,如果是接这关系运算符后面,必须保证 子查询只返回一个值
--查询六期班的学员信息
select * from Student where ClassId=(select ClassId from grade where classname='八期班')
--子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
select * from Student where ClassId=(select ClassId from grade)
--查询八期班以外的学员信息
--当子查询返回多个值(多行一列),可以使用in来指定这个范围
select * from Student where ClassId in(select ClassId from grade where classname<>'八期班')
--当没有用 EXISTS 引入子查询时,在选择列表中只能指定一个表达式。如果是多行多列或者一行多列就需要使用exists
--使用 EXISTS 关键字引入子查询后,子查询的作用就相当于进行存在测试。外部查询的 WHERE 子句测试子查询返回的行是否存在
select * from Student where  EXISTS(select * from grade)
select * from Student where  ClassId in(select * from grade)

--2.子查询做为结果集--
select top 5 * from Student --前五条
--使用top分页
select top 5 * from Student where StudentNo not in(select top 5 studentno from Student)
--使用函数分页  ROW_NUMBER() over(order by studentno),可以生成行号,排序的原因是因为不同的排序方式获取的记录顺序不一样
select ROW_NUMBER() over(order by studentno),* from Student
--查询拥有新生成行号的结果集  注意:1.子查询必须的别名  2.必须为子查询中所有字段命名,也就意味着需要为新生成的行号列命名
select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>0 and temp.id<=5
select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>5 and temp.id<=10
select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where temp.id>10 and temp.id<=15

--3.子查询还可以做为列的值
select (select studentname from student where studentno=result.studentno),(select subjectname from subject where subjectid=result.SubjectId), StudentResult from Result

--使用Row_number over()实现分页
--1.先写出有行号的结果集
select ROW_NUMBER() over(order by studentno),* from Student
--2.查询有行号的结果集 子查询做为结果集必须添加别名,子查询的列必须都有名称
select * from (select ROW_NUMBER() over(order by studentno) id,* from Student) temp where id>0 and id<=5
--查询年龄比“廖杨”大的学员,显示这些学员的信息
select * from Student where BornDate<(select BornDate from Student where StudentName='廖杨')
--查询二期班开设的课程
select * from Subject where ClassId=(select ClassId from grade where classname='二期班')
--查询参加最近一次“office”考试成绩最高分和最低分
--1查询出科目 ID
select subjectid fromSubjectwhereSubjectName='office'--2.查询出这一科目的考试日期select MAX(ExamDate)fromResultwhereSubjectId=(select subjectid fromSubjectwhereSubjectName='office')--3,写出查询的框架select MAX(StudentResult),MIN(StudentResult)fromResultwhereSubjectId=()andExamDate=()--4.使用子查询做为条件select MAX(StudentResult),MIN(StudentResult)fromResultwhereSubjectId=(select subjectid fromSubjectwhereSubjectName='office')andExamDate=(select MAX(ExamDate)fromResultwhereSubjectId=(select subjectid fromSubjectwhereSubjectName='office'))

16.表连接Join

--1.inner join :能够找到两个表中建立连接字段值相等的记录
--查询学员信息显示班级名称
select Student.StudentNo,Student.StudentName,grade.classname
from Student
inner join grade on Student.ClassId=grade.ClassId

--左连接: 关键字前面的表是左表,后面的表是右表
--左连接可以得到左表所有数据,如果建立关联的字段值在右表中不存在,那么右表的数据就以null值替换
select PhoneNum.*,PhoneType.*
from   PhoneNum 
left join  PhoneType on PhoneNum.pTypeId=PhoneType.ptId
--右连接: 关键字前面的表是左表,后面的表是右表
--右连接可以得到右表所有数据,如果建立关联的字段值在右左表中不存在,那么左表的数据就以null值替换
select PhoneNum.*,PhoneType.*
from   PhoneNum 
right join  PhoneType on PhoneNum.pTypeId=PhoneType.ptId
--full join :可以得到左右连接的综合结果--去重复
select PhoneNum.*,PhoneType.*
from   PhoneNum 
full join  PhoneType on PhoneNum.pTypeId=PhoneType.ptId

17.事务

一种处理机制。以事务处理的操作,要么都能成功执行,要么都不执行。

事务的四个特点 ACID:

A:原子性:事务必须是原子工作单元;对于其数据修改,要么全都执行,要么全都不执行。它是一个整体,不能再拆分
C:一致性:事务在完成时,必须使所有的数据都保持一致状态。。某种程度的一致
I:隔离性:事务中隔离,每一个事务是单独的请求将单独的处理,与其它事务没有关系,互不影响
D:持久性:如果事务一旦提交,就对数据的修改永久保留
使用事务:

将你需要操作的sql命令包含在事务中。

1.在事务的开启和事务的提交之间
2.在事务的开启和事务的回滚之间

三个关键语句:

开启事务:begin transaction
提交事务:commit transaction
回滚事务:rollback transaction
declare @num int =0 --记录操作过程中可能出现的错误号
begin transaction
  update bank set cmoney=cmoney-500 where name='aa'
  set @num=@num+@@ERROR
  --说明这一句的执行有错误  但是不能在语句执行的过程中进行提交或者回滚
  --语句块是一个整体,如果其中一句进行了提交或者回滚,那么后面的语句就不再属于当前事务,
  --事务不能控制后面的语句的执行

 update bank set cmoney=cmoney+500 where name='bb' set @num=@num+@@ERROR select * from bank  if(@num<>0 ) --这个@@ERROR只能得到最近一一条sql语句的错误号   begin    print '操作过程中有错误,操作将回滚'    rollback transaction  end   else    begin    print '操作成功'    commit transaction   end

    --事务一旦开启,就必须提交或者回滚
    --事务如果有提交或者回滚,必须保证它已经开启

18.视图

视图就是一张虚拟表,可以像使用子查询做为结果集一样使用视图。

select * from vw_getinfo
使用代码创建视图。

语法:

create view vw_自定义名称
as
查询命令
go
--查询所有学员信息
if exists(select * from sysobjects where name='vw_getAllStuInfo')
 drop view vw_getAllStuInfo
go --上一个批处理结果的标记
create view vw_getAllStuInfo
as
--可以通过聚合函数获取所以记录数
 select top (select COUNT(*) from Student) Student.StudentNo,Student.StudentName,grade.ClassId,grade.classname from Student
inner join grade on Student.ClassId=grade.ClassId  order by StudentName --视图中不能使用order by
--select * from grade --只能创建一个查询语句
--delete from grade where ClassId>100 --在视图中不能包含增加删除修改
go

--使用视图。。就像使用表一样
select * from vw_getAllStuInfo
--对视图进行增加删除和修改操作--可以对视图进行增加删除和修改操作,只是建议不要这么做:所发可以看到:如果操作针对单个表就可以成功,但是如果 多张的数据就会报错:不可更新,因为修改会影响多个基表。
update vw_getAllStuInfo set classname='asdas' ,studentname='aa' where studentno=1

19.触发器

触发器:执行一个可以改变表数据的操作(增加删除和修改),会自动触发另外一系列(类似于存储过程中的模块)的操作。

语法:

create trigger tr_表名_操作名称
on 表名 after|instead of 操作名称
as
go
if exists(select * from sysobjects where name='tr_grade_insert')
 drop trigger tr_grade_insert
go
create trigger tr_grade_insert
on grade for  insert  ---为grade表创建名称为tr_grade_insert的触发器,在执行insert操作之后触发
as
declare @cnt int
set @cnt = (select count(*) from student)
 select * ,@cnt from student
select * from grade
go
--触发器不是被调用的,而是被某一个操作触 发的,意味着执行某一个操作就会自动触发 触发器
insert into grade values('fasdfdssa')
---替换触 发器:本来需要执行某一个操作,结果不做了,使用触 发器中的代码语句块进行替代

if exists(select * from sysobjects where name='tr_grade_insert')
 drop trigger tr_grade_insert
go
create trigger tr_grade_insert
on grade instead of insert  ---为grade表创建名称为tr_grade_insert的触发器,在执行insert操作之后触发
as
declare @cnt int
set @cnt = (select count(*) from student)
 select * ,@cnt from student
select * from grade
go

insert into grade values('aaaaaaaaaaaa')
go

---触 发器的两个临时表:
--inserted: 操作之后的新表:所有新表与原始的物理表没有关系,只与当前操作的数据有关
--deleted:操作之前的旧表:所有新表与原始的物理表没有关系,只与当前操作的数据有关

if exists(select * from sysobjects where name='tr_grade_insert')
 drop trigger tr_grade_insert
go
create trigger tr_grade_insert
on grade after insert
as
 print '操作之前的表:操作之前,这一条记录还没有插入,所以没有数据'
 select * from deleted
 print '操作之后的表:已经成功插入一条记录,所有新表中有一条记录'
 select * from inserted 
go
--测试:
insert into grade values('aaaaa')

if exists(select * from sysobjects where name='tr_grade_update')
 drop trigger tr_grade_update
go
create trigger tr_grade_update
on grade after update
as
 print '操作之前的表:存储与这个修改操作相关的没有被修改之前的记录'
 select * from deleted
 print '操作之后的表:存储这个操作相关的被修改之后 记录'
 select * from inserted 
go
--测试
update grade set classname=classname+'aa' where  ClassId>15

if exists(select * from sysobjects where name='tr_grade_delete')
 drop trigger tr_grade_delete
go
create trigger tr_grade_delete
on grade after delete
as
 print '操作之前的表:存储与这个修改操作相关的没有被删除之前的记录'
 select * from deleted
 print '操作之后的表:存储这个操作相关的被删除之后 记录--没有记录'
 select * from inserted 
go

--测试
delete from grade whe


  • 上一条:
    MySQL日志管理详解
    下一条:
    mysql ERROR 1044 (42000): Access denied for user ''@'localhost' to database
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客