您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Mysql基础知识点汇总_MySQL

2024/6/21 2:29:24发布31次查看
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'1990-1-1' and address='广州传智播客'
--指定区间范围
select studentno,studentname,sex,borndate,address from student where borndate >='1990-1-1' and borndate= =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,'你懂的')
--sudyfsagfyas@12fasdf6.fsadfdsaf
declare @email varchar(50)='sudyfsagfyas@12fasdf6.fsadfdsaf'
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 =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@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@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 = 0 and temp.id5 and temp.id10 and temp.id0 and id15
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 where classid>15
20.存储过程
存储过程就相当于c#中的方法
参数,返回值,参数默认值,参数:值的方式调用
在调用的时候有三个对应:类型对应,数量对应,顺序对应。
创建语法:
create proc usp_用户自定义名称
对应方法的形参 --(int age, out string name)
as
对应方法体:创建变量,逻辑语句,增加删除修改和查询..return返回值
go
调用语法:
exec 存储过程名称 实参,实参,实参 ...
--获取所有学员信息
if exists(select * from sysobjects where name='usp_getallstuinfo')
 drop proc usp_getallstuinfo
go
create procedure usp_getallstuinfo
as
 select * from student
go
--调用存储过程,获取的有学员信息
execute usp_getallstuinfo
--exec sp_executesql  'select * from student'
--查询指定性别的学员信息
go
if exists(select * from sysobjects where name='usp_getallstuinfobysex')
 drop proc usp_getallstuinfobysex
go
create procedure usp_getallstuinfobysex
 @sex nchar(1) --性别  参数不需要declare
as
 select * from student where sex=@sex
go
--调用存储过程,获取指定性别的学员信息
exec usp_getallstuinfobysex '女'
--创建存储过程获取指定班级和性别的学员信息
go
if exists(select * from sysobjects where name='usp_getallstuinfobysexandclassname')
 drop proc usp_getallstuinfobysexandclassname
go
create procedure usp_getallstuinfobysexandclassname
 @classname nvarchar(50), --班级名称
 @sex nchar(1)='男'--性别   有默认的参数建议写在参数列表的最后
as
 declare  @classid int ---班级id
set @classid=(select classid from grade where classname=@classname) --通过参数班级名称获取对应的班级id
 select * from student where sex=@sex and classid=@classid
go
--执行存储过程获取指定班级和性别的学员信息
--exec usp_getallstuinfobysexandclassname '八期班'
exec usp_getallstuinfobysexandclassname default, '八期班'  --有默认值的参数可以传递default
exec usp_getallstuinfobysexandclassname @classname='八期班'    --也可以通过参数=值的方式调用
exec usp_getallstuinfobysexandclassname @classname='八期班'  ,@sex='女'
exec usp_getallstuinfobysexandclassname @classname='八期班',@sex='女'
--创建存储过程,获取指定性别的学员人数及总人数
go
if exists(select * from sysobjects where name='usp_getcountbysexandclassname')
 drop proc usp_getcountbysexandclassname
go
create procedure usp_getcountbysexandclassname
@cnt int=100 output, --output标记说明它是一个输出参数。output意味着你向服务器请求这个参数的值,那么在执行的时候,服务器发现这个参数标记了output,就会将这个参数的值返回输出
@totalnum int =200output, --总人数
@classname nvarchar(50), --输入参数没有默认值,在调用的时候必须传入值
@sex nchar(1)='男'--输入参数有默认值,用户可以选择是否传入值
as
 declare  @classid int ---班级id
 set @classid=(select classid from grade where classname=@classname) --通过参数班级名称获取对应的班级id
 select * from student where sex=@sex and classid=@classid
set @cnt= (select count(*) from student where sex=@sex and classid=@classid) --获取指定班级和性别的总人数
set @totalnum=(select count(*) from student) ----获取总人数
go
--调用存储过程,获取指定性别的学员人数及总人数
declare @num int,@tnum int
exec usp_getcountbysexandclassname @cnt=@num output ,@totalnum=@tnum output , @classname='八期班'
print @num
print @tnum
print '做完了'
---获取指定班级的人数
if exists(select * from sysobjects where name='usp_getcount')
 drop proc usp_getcount
go
create procedure usp_getcount
 @classname nvarchar(50)='八期班'
as
declare @classid int=(select classid from grade where classname=@classname)
 declare @cnt int
set @cnt =(select count(*) from student where classid=@classid)
--return 只能返回int整数值
--return '总人数是'+cast(@cnt as varchar(2))
return @cnt
go
--调用存储过程,接收存储过程的返回值
declare @count int
--set @count=(exec usp_getcount)
exec @count=usp_getcount '八期班'
print @countif exists(select*from sysobjects where name='usp_getclasslist')
 drop proc usp_getclasslist
go
create procedure usp_getclasslist
asselect classid,classname from grade
go
21.分页存储过程
if exists(select * from sysobjects where name='usp_getpagedata')
 drop proc usp_getpagedata
go
create procedure usp_getpagedata
@totalpage int output,--总页数
@pageindex int =1 ,--当前页码,默认是第一页
@pagecount int =5 --每一页显示的记录数
as
select * from (select row_number() over(order by studentno) id,* from student) temp where temp.id>(@pageindex-1)*@pagecount and temp.idset @totalpage=ceiling((select count(*) from student)*1.0/@pagecount)
go
22.索引
select * from sysindexes
--create  index ix_student_studentname
--on 表名(字段名)
--clustered index:聚集索引  nonclustered index--非聚集索引
if exists(select * from sysindexes where name='ix_student_studentname')
 drop index student.ix_student_studentname
go
create clustered index ix_student_studentname
on student(studentname)
--如果是先创建主键再创建聚集索引就不可以,因为主键默认就是聚集索引
--但是如果先创建聚集索引,那么还可以再创建主键,因为主键不一定需要是聚集的
23.临时表
--创建局部临时表
create table #newgrade
(
 classid int ,
 classname nvarchar(50)
)
---局部临时表只有在当前创建它的会话中使用,离开这个会话临时表就失效.如果关闭创建它的会话,那么临时表就会消失
insert into #newgrade select * from  grade
select * from #newgrade
select * into #newnewnew from grade
select * into newgrade from #newgrade
--创建全局临时表:只要不关闭当前会话,全局临时表都可以使用,但是关闭当前会话,全局临时表也会消失
create table ##newgrade
(
 classid int ,
 classname nvarchar(50)
)
drop table ##newgrade
select * into ##newgrade from grade
select * from ##newgrade
--创建表变量
declare @tb table(cid int,cname nvarchar(50))
insert into @tb select * from grade
select * from @tb
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product