本帖最后由 武汉18期李欣康 于 2022-8-10 22:29 编辑
索引作用:
索引分类
1.普通索引
show index from emp;查看索引
create index xiaoli on emp(sid); 为emp表中的sid创建个索引xiaoli
create index xiaoli1 on emp(sid,name)为emp表中的sid,name创建索引xiaoli2
alter table emp drop index xiaoli; 删除索引
唯一索引:索引列必须为空,可以为空
create unique index aa on emp(sid); 创建唯一索引
3主键索引:和主键约束相辅相成
注:添加一个主键约束就是添加了主键索引,主键索引就是主键约束
数据库视图
特点:
1.视图是由基本表产生的虚表
2.视图的更新和删除会影响基本表
3,基本表的更新和删除也会影响视图
create view dcs as(select sid ,name,age from emp);创建视图
undate dcs set name="zhangsan" where sid=1789; 修改视图
same="张三" where sid=1789;修改基本表
drop view dcs 删除视图
DDL:数据库定义语言(对表和表结构操作)
create
alter table
drop
DML:数据库的操作语言(表数据操作)
insert into
delete
undate
select
数据库约束
not null 非空约束
primary key 主键约束
auto_increment 自增长约束
default 默认值约束 前四种都是对表结构的约束
foreign key 外键约束 对表和表之间的约束
外键约束:用来保持数据的一致性和完整性
show create table dept; 查看表约束
create table dcs1(id int(5)PRIMARY key,name varchar(10))ENGINE=innodb;
创建dcs1表,修改类型为innobd
create table dcs2(sid int(5)primary key,sname varchar(10),CONSTRAINT xiaoli foreign key dcs2(sid) REFERENCES dcs1(id))engine=INNODB;
创建dcs2表同时创建外键约束
如果dcs1和dcs2存在外键约束,dcs1(主表) dcs2(子表)
主表中不存在的数据,不能在子表中进行插入
删除数据
delete from dcs1 where id=1;
delete from dcs2 where sid=1;
如果要删除主表数据,要先删除子表相关联数据
alter table dcs2 drop foreing key xiaoli;删除外键约束
存储过程
存储过程=sql语句集合+控制语句
固定格式
create procedure 存储过程名称(参数名,数据类型) ##创建存储过程
begin ##存储过程开始
存储过程体
end
call 存储过程名称() # 调用存储过程
drop procedure if exists dcs18;
create procedure dcs18(n int) #n变量 int是数据类型
begin
drop table if exists aa;
create table aa(id int(5)primary key auto_increment,score int(5));
insert into aa values (1,88),(2,75);
insert into aa values (3,66),(4,99);
select*from aa;
select*from aa where id=n;#带参数查询
end
call dcs18(3)#进行实参查询
if条件判断语句
单分支
if 条件 then
sql语句1
else
sql语句2
end if
单分支查询
drop procedure if exists dcs18;
create procedure dcs18(n int) #n变量 int是数据类型
begin
drop table if exists aa;
create table aa(id int(5)primary key auto_increment,score int(5));
insert into aa values (1,88),(2,75);
insert into aa values (3,66),(4,99);
/*select*from aa;
select*from aa where id=n;#带参数查询*/
if n=0 then
select count(*) from aa;
else
select*from aa order by score desc;
end if;
end
call dcs18(3)#进行实参查询
多分枝(有几个if 结束就要写几个end if)
if 条件1 then
sql语句1
else if 条件2 then
sql语句2
else if 条件3 then
sql语句3
else 都不满足做其他处理
sql语句4
end if;
end if;
end if;
drop procedure if exists dcs18;
create procedure dcs18(n int) #n变量 int是数据类型
begin
drop table if exists aa;
create table aa(id int(5)primary key auto_increment,score int(5));
insert into aa values (1,88),(2,75);
insert into aa values (3,66),(4,99);
insert into aa values (5,55),(6,56);
insert into aa values (7,12),(8,11);
if n=0 then
select count(*) from aa;
else if n>0 and n<=8 then
select*from aa order by score desc;
else if n>8 then
select max(score) from aa;
else
select*from aa;
end if;
end if;
end if;
end
call dcs18(4)#进行实参查询
declarare i 声明变量i
declare i int(5)default(select count(*) from aa);declare
while 语句格式:
while 条件 do
执行循环体
end while 结束循环
|
|