MySQL基础操作总结

一、常见函数

1.字符函数

(1)length(str):字节长度

	select length('rose');#4
	select length('张三');#2
	show variables like '%char%';#查看与char相关的属性值

(2)concat(,):拼接字符

    select concat(id,"_",ifnull(`name`,'')) as ms from testinfo;

(3)upper()、lower():大小写

	select upper("Jone");
	select lower('Jone');

(4)substr(str,pos):从第pos位置截取到最后
#substr(str,pos,length):从第pos位置截取length长度 #mysql中下标从1开始

	select substr("123456789",7) as rs;# 789
	select substr("123456789",1,5) as rs;# 12345
	select concat(id,'_',
	upper(substr(ifnull(`name`,'null'),1,1)),lower(substr(ifnull(`name`,'null'),2))) 
	from testinfo;#实现字符拼接、姓名判空和姓名首字母大写功能

(5)instr():在str中第一次出现的下标,没有返回0

	select `name`,instr(`name`,'e') as 'position' from testinfo;
	#返回restinfo表中name值第一次出现e的位置,并重命名为position

(6)trim:去前后空格、字符

	select length(trim('    will    ')) as trim;
	select trim('i' from 'iiiiwilliiii') as trim;# 去前后i

(7)lpad():用指定的字符左填充成指定长度

	select lpad("will",10,"*");

(8)rpad():用指定的字符右填充成指定长度

	select rpad("will",10,"*");

(9)replace():替换

	select replace("i lave yau","a","o") as u;

2.数学函数

(1)round:四舍五入

	select round(-12.5);#按绝对值
	select round(12.564,2);#保留两位

(2)ceil;向上取整,>=该数的最小整数

	select ceil(1.01);

(3)floor:向下取整,<=该数的最大整数

	select floor(-1.6);

(4)truncate:截断

	select truncate(1.415,2);

(5)mod:取余 a-a/b*b , 结果正负和被除数10有关

	select mod(10,-3);

(6)rand():随机数

	select rand();

3.日期函数

(1)now:返回当前日期+时间

	select now();

(2)curtime:当前时间

	select curtime();

(3)year:年,monthname():英文月份

	select year(now());
	select year('1999-10-12') as;
	select monthname(now());

(4)str_to_date():转化格式化日期
/* 1999-09-02 13:09:01
%Y 四位的年份 1999
%y 两位的年份 99
%m 单位数月份 9
%c 两位数月份 09
%d 两位数的日 02
%H 24制的小时 13
%h 12制小时 1
%i 两位数分钟 09
%s 两位数秒 01
*/

	select str_to_date("9-02-1999","%c-%d-%Y");

(5)date_format():日期转字符

	select date_format(str_to_date("9-02-1999","%c-%d-%Y"),'%Y年%c月%d日') as 日期;

(6)第一个日期减去第二个日期的天数

	select datediff(now(),'1999-10-12');

4.其它函数

	select database();#查询当前使用的数据库
	select version();#查询当前数据库版本
	select user();#查询当前用户
	select password(str)#自动加密
	select md5(str)#md5加密
	select id , `name`,ifnull(`name`,'null') result from testinfo;#判空函数
	select distinct id from testinfo;#去重
	show tables;#展示当前数据库中所有的表名
	desc testinfo;#查询表结构

5.流程控制函数

(1)if:if else

	#判空,如果为空则为‘’,否则不变
	select if(`name`<=> null,'',`name`) as 'name' from testinfo;

(2) case:

/*1)类似switch case效果 case 判断条件 when 常量1 then 值/语句
when 常量2 then 值/语句
when 常量3 then 值/语句
else 值/语句
end
*/

	select `name`,
	case id
	when 1 then id*1.414
	when 2 then id*2.758
	when 3 then id*3.141
	else id
	end as newid from testinfo;

/*2)多重if效果 case when 条件1 then 值/语句
when 条件2 then 值/语句
when 条件3 then 值/语句
else 值/语句
end
*/

	select id,
	case
	when id%2=0 then '偶数'
	when id%2!=0 then '奇数'
	else id
	end as 奇偶性,`name` from testinfo;

6.分组函数:统计使用

#1.分类:sum 求和、avg 平均值、max 最大值、min 最小值、count 计数

	select 
	id,sum(id) sumid,avg(id) avgid,max(id) maxid,min(id) minid,count(id) countid 
	from testinfo;

#2.传参类型 /sum,avg:数值型 max、min、count:任何类型/

	select `name`,sum(`name`) sumname,avg(`name`) avgname,max(`name`) maxname,
	min(`name`) minname,count(`name`) countname  from testinfo;

#3.是否忽略null
#sum,avg,max、min、count:忽略

#4.与distinct一起使用

	select sum(distinct id) sumid,avg(distinct id) avgid,max(distinct id) maxid,
	min(distinct id) minid,count(distinct id) countid from testinfo;

#5.count()的详细介绍 /效率:MYISAM存储引擎下:count()效率最高; INNODB存储引擎下count(*)与count(1)差不多,但比count(字段)快
*/

select count(`name`) 'countname',count(*) 条数,count(1) 条数,count(2) 条数 from testinfo;

#6.和分组函数一起查询的字段有限制:group by后的字段可以,别的不行

二、DQL:数据查询语言

1.条件查询

/* 一、条件运算符: <,>,=,<>,!=,>=,<=
二、逻辑运算符 &&,||,! and,or,not
三、模糊运算符 like,between and,in,is null,is not null
*/

	select * from testinfo where id*12<10000;
	select `name` from testinfo where `name`<>'john'; 
	select * from testinfo where `name` is not null and id<=100;

– like :
/*通配符:
%:任意多个字符
_:单个字符
*/

	select * from testinfo where `name` like '%m%';
	select * from testinfo where `name` like 'm__e%';

#转译

	select * from testinfo where `name` like 'm_\_e%';
	select * from testinfo where `name` like 'm_@_e%' escape '@';

– between and:>= a && <= b、包含端点

	select distinct * from testinfo where id between 1 and 4;

– in:列表中的值类型需统一或兼容

	select * from testinfo where id in (1,3,5,7,9);

– is null

	select id from testinfo where `name` is null;

=:后不能加null
#安全等于:<=>: = 加 is null

	select id from testinfo where `name` <=> null;

#isnull():为空返回1,不为空返回0

	select isnull(name),name from testinfo;

3.排序查询

	select * from testinfo order by id desc;-- 降序
	select * from testinfo order by id asc;-- 升序
	select * from testinfo order by id;-- 默认升序

– 按字段排序

	select * from testinfo where id%2<>0 order by name;

– 按表达式排序

	select * from testinfo where id%2<>0 order by -id*10;

– 按别名排序

	select concat(ifnull(`name`,'null'),id) as message from testinfo order by message desc;

– 按多字段排序

	select * from testinfo order by length(ifnull(`name`,'null')),id ; 

4.分组查询

#简单的分组查询

	select max(`name`) firstname from testinfo group by id;
	select count(*),id from testinfo group by id;

#添加筛选条件

	select round(avg(id),1),`name` from testinfo where `name` like '%m%' group by `name`;
	select min(`name`) from testinfo where `name` is not null group by id;

#添加复杂的筛选条件
#查询姓名不为空的每个id下的姓名个数小于四的姓名个数 根据1的结果进行筛选

– 1

	select count(*),id from testinfo where `name` is not null group by id;

– 2

	select count(*),id from testinfo 
	where `name` is not null
	group by id 
	having count(*)<4;

5.多表查询

	select * from student;
	select * from words;

/* sq92:内连接,也支持一部分外连接(用于oracle,Sql Server;mysql不支持);
sq99:内连接、外连接(左外连接、右外连接)、交叉连接
内连接:等值连接、非等值连接、自连接
外连接:左外连接、右外连接、全外连接
交叉连接*/

一、sq92语法的连接查询

(1) 等值连接、为表起别名

	select w.UserID,`name`,WordsTime,WordsTitle,WordsContent 
	from student as s,words as w 
	where s.stu_id = w.UserID
	and w.WordsTime < now() and w.WordsTime > '2010-00-00';
	select w.UserID,`name`,WordsTime,WordsTitle,WordsContent 
	from student as s,words as w 
	where s.stu_id = w.UserID
	and w.WordsTime bettwen '2010-01-01' and now()
	group by name
	having count(*)=1
	order by UserID desc;

(2)非等值连接:相当于笛卡尔积去除条件不相等的部分

	select w.UserID,`name`,WordsTime,WordsTitle,WordsContent 
	from student as s,words as w 
	where s.stu_id != w.UserID
	and w.WordsTime between '2010-00-00' and now();

(3) 自连接:自己和自己连接,利用别名来查询本表内容

	select u.stu_id ,u.`name`,s.stu_id,s.`name`
	from student u,student s
	where u.stu_id = s.stu_id;

二、sq99语法的连接查询
/内连接 inner
外连接 left,right,full
交叉连接
/

(1)内连接 inner可省 多表的交集

	select w.UserID,`name`,WordsTime,WordsTitle,WordsContent 
	from student as s
	inner join words as w 
	on s.stu_id = w.UserID ;

(2)外连接 left outer join:左表为主表,显示左表全部字段,右表匹配不上的则显示空;
right outer join:右表为主表,显示左表全部字段,左表匹配不上的则显示空;
full outer join:没有主表,显示左右表交集和非交集部分,相当于左外和右外的结合

	select w.UserID,WordsTime,WordsTitle,WordsContent 
	from student as s
	right outer join words as w 
	on s.stu_id = w.UserID
	where s.stu_id is null ;

(3)交叉连接:笛卡尔乘积

	select s.*,w.* 
	from student as s
	cross join words as w;

#sql92 pk sql99
/* sql99功能更多、可读性更强
*/

6.子查询:出现在其它语句中的select语句

/*
可以出现的位置:
select后面:支持标量子查询
from后面:支持表子查询
where和having后面:标量子查询、列子查询、行子查询
exists后面(相关子查询):表子查询
结果集的行列数不同:一行一列(标量子查询)、列子查询(一列多行)、
行子查询(一行多列)、表子查询(多行多列)
*/

一、 where和having后面:

(1)标量子查询:搭配着单行操作符使用 > < >= <= <>

	select *
	from student 
		where birthday<=(
		select birthday 
		from student 
		where name = "小李"
	);

(2)列子查询:搭配着多行操作符使用 in any/some all
(3)in等价于 ‘=any’;not in等价于‘not all’
(4)行子查询:(a1,b1)=(select min(a),min(b) from a,b) ;

二、select后面:

	select name,
	(	select count(*) 
		from words w
		where w.UserID=s.stu_id) 消息
	from student s;

三、from后面:

	select s.*,t.n 英文名
	from (
	select id+10 nid,name n from testinfo
	)t,student s
	where t.nid = s.stu_id;

四、exists后面:存在则为1,否则为0

	select * 
	from words w
	where UserID not in(
	select stu_id from student
	);
	select * 
	from words w
	where not exists(
	select stu_id from student s where w.UserID = s.stu_id
	);

7.分页查询:分页显示时使用 limit 开始条目(从0开始),条目个数

(1) 公式:limit (page-1)*size,size

	select * from testinfo limit 0,5;

(2)从0开始可以省略第一个参数

	select * from words order by WordsTime desc limit 3;

8.联合查询

union 将多条查询语句的结果合并成一个结果:
/*要求多表查询语句的查询列数需一致
要求多列间的顺序、类型最好一致
union默认去重,union all不去重
*/

	select id ,name from testinfo where name is not null
	union
	select stu_id,name from student where name is not null;

三、DML语言:数据管理语言

/*
插入:insert
删除:delete
更改:update
*/

1.插入语句

方式一:

	insert into student(stu_id,name,address,birthday)
	values(14,"小陈","河南","1999-09-09");

前后应对应一致:

	insert into student(stu_id,name,birthday)
	values(15,"小苏","1999-09-09");

可省略字段名:

	insert into student
	values(16,"小刘","四川","1999-09-08");

支持多条插入:

	insert into student(stu_id,name,address,birthday)
	values(18,"小陆","河南","1999-09-09"),
	(19,"小贺","河南","1999-09-09"),
	(20,"小周","河南","1999-09-09");

支持子查询:

	insert into student(stu_id,name,address,birthday)
	select 21,"小吴","北京","1981-04-02";

方式二:不支持多条插入,不支持子查询

	insert into student
	set stu_id=17,name="小董",address="黑龙江",birthday=now();

2.修改语句

	SET SQL_SAFE_UPDATES = 0;#更改数据库更新模式
	update student 
	set birthday='2000-10-12'
	where name = '小王'; 
	select * from student;

多表修改:

	update words w
	left join student s on w.UserID = s.stu_id
	set WordsContent = '放假去约会'
	where name = '小王';

3.删除语句

	delete w
	from words w
	inner join student s
	where s.name='小王';

清空整个表:
/*
delete:删除整表后,自增长列从断点开始 有返回值 可以回滚 可以加where 效率低一丢丢
truncate:删除整表后,自增长列从1开始 无返回值 不能回滚 不能加where 效率高一丢丢
*/

	delete from a;
	truncate table a;

四、DDL:数据定义语言

1. 库的管理

(1)库的创建

	create database if not exists ch12;
	use ch12;

(2)更改库的字符集

	alter database ch12 character set gbk;

(3)库的删除

	drop database if exists ch12;

2. 表的管理

(1)表的创建

create table book(
id int ,
name varchar(20),
price double,
authorId int,
publishDate Datetime
);
desc book;#查看表结构

(2)表的修改

  • 1)列的修改
	alter table book change column publishDate pbDate datetime;
  • 2)修改列类型或约束
	alter table book modify column pbDate timestamp;
  • 3)列的增加
	alter table book add column annual double;
	alter table book add column testF int first;#添加到第一个位置
	alter table book add column testS int after testF;#添加到指定列后面
  • 4)删除列
	alter table book drop column annual;
  • 5)表的重命名
	alter table book rename to book_autor;

(3)表的删除

	drop table if exists book_autor;

(4)表的复制

	insert into book 
	values(1,"流浪地球",50.00,10,"2018-10-01"),
	(2,"平凡的世界",50.00,11,"2017-10-01"),
	(3,"三体",50.00,10,"2016-10-01"),
	(4,"求魔",50.00,16,"2019-10-01"),
	(5,"斗罗大陆",50.00,17,"2018-10-01"),
	(6,"龙族",50.00,12,"2018-10-01");
  • 1)复制表的结构
	create table copy like book;
  • 2)复制表的结构+数据
	create table copy2 
	select * from book;
  • 3)复制表的结构+部分数据
	create table copy3 
	select * from book
	where id>=3;
  • 4)复制表的部分结构
	create table copy4 
	select id,name from book where 0;

3.常见的数据类型

/*数值型:
整型:tinyint【1字节】、smallint【2字节】、mediumint【3字节】、int,integer【4字节】、bigint【8字节】
小数:(M,D)可省略
定点小数:dec(M,D)、deciaml(M,D)
浮点小数:float(M,D)、double(M,D)
字符型:
较短:(M)=(最长字符数)
char(M):定长字符 可省略M,默认为1 耗费空间 效率高
varchar(M):可变字符 不可省略M 节省空间 效率稍低
较长:
text
blob(较大的二进制)
枚举类型:只能插入单个指定字符,不区分大小写
enum(‘a’,‘b’,‘c’,‘d’)
insert into t values(‘a’)
集合类型:可插入多个指定字符,不区分大小写
set(‘a’,‘b’,‘c’,‘d’)
insert into t values(‘a,b’)
日期型:
date ‘1999-10-12’ 4字节
datetime ‘1999-10-12 00:00:00’ 不受时区影响 8字节 1000-9999
timestamp ‘19991012000000’ 受时区和mysql版本影响 4字节 1970-2038

    set time_zone = '+9:00';	-- 设置时区						
   show variables like 'time_zone';-- 查询时区

time ‘00:00:00’ 3字节
year ‘1999’ 1字节

选则类型原则:越简单越好、越小越好
*/

(1)如何设置有无符号

	drop table if exists test;
	create table test(
	t1 int,			#默认有符号
	t2 int unsigned,#无符号
	t3 int(7) zerofill#括号内长度代表显示长度
	);
	insert into test values(-123456,-1,123);-- 越界
	insert into test values(-123456,0,456);-- 不越界
	select * from test;
	desc test;

(2)(整数部位+整数部位,小数部位)

	drop table if exists test;
	create table test(
	t1 float(5,2),#默认随着插入值的精度变化
	t2 double(5,2),#默认随着插入值的精度变化
	t3 decimal(5,2)#默认(10,0)
	);
	insert into test values(1.2,1.23,1.23);
	select * from test;

五、常见约束

/*含义:限制表中的数据,以保证数据的可靠性和准确性
六大约束:
not null:非空
default:默认,保证该字段有默认值
primary key:主键不为空不重复
unique:不重复但可以为空
check:检查(mysql不支持)
foreign key:外键 限制两表关系,元素来自于主表
约束分类:
列级约束:六大约束都可以写,但foreign key 无效
表级约束:除了非空、默认其它的都支持
主键与唯一的对比:
保证唯一性 非空 一个表中可以有几个 是否允许组合键(即多个字段组成的联合键)
主键 是 是 至多有一个 允许
唯一 是 否 可以有多个 允许
外键:
1.要求在从表设置外键关系
2.从表的外键列类型要和主表的关联列相同或兼容
3.主表的关联列必须是一个key(一般是主键或唯一)
4.插入数据时先插入主表内容,删除时先删除从表内容
*/

	use ch10;

1.创建表时添加约束

(1)添加列级约束

	create table yueshu(
	id int primary key,
	name varchar(20) not null,
	gender char(1) check(gender='男' or gender='女'),
	seatId int unique,
	age int default 18,
	majorId int references major(id)
	);
	create table major(
	id int primary key,
	majorName varchar(20)
	);
	desc yueshu;
	show index from yueshu;

(2)添加表级约束 (constraint 约束名)可省

	drop table if exists yueshu;
	create table yueshu(
	id int,
	name varchar(20),
	gender char(1),
	seatId int,
	age int,
	majorId int,
	constraint pk primary key(id),
	constraint uq unique(seatId),
	constraint ck check(gender='男' or gender='女'),
	constraint fk_yueshu_major foreign key(majorId) references major(id)
	);
	show index from yueshu;
	show variables like 'character_set_database';

2.修改表时添加约束

(1) 添加列级约束

	alter table major modify column majorName varchar(20) not null; 

(2)添加表级约束

	alter table major add unique(majorName);
	alter table stuinfo add constraint fk_stuinfo_major foreign key(majorid) references major(id);

3.修改表时删除约束

	alter table major modify column majorName varchar(20) null;
	alter table major drop index majorName;-- 删除唯一键
	alter table major frop primary key;-- 删除主键

4. 标识列

/* 自增长列
标识列不一定和主键搭配,但必须是一个key
一个表只能有一个自增长列
标识列的类型只能是数值型
可以通过set auto_increment_increment=10;设置步长
*/

(1)创建表时设置

	drop table if exists yueshu;
	create table yueshu(
	id int auto_increment,-- 此处添加
	name varchar(20),
	gender char(1),
	seatId int,
	age int,
	majorId int,
	constraint pk primary key(id),
	constraint uq unique(seatId),
	constraint ck check(gender='男' or gender='女'),
	constraint fk_yueshu_major foreign key(majorId) references major(id)
	);
	insert into major values(2,"软件工程");
	insert into yueshu values(null,'jack','男',6,10,2);
	select * from yueshu;
	show variables like '%auto_increment%';#步长和起始号

步长可更改,起始号不能更改

	set auto_increment_increment=10;
	insert into yueshu values(null,'jack','男',1,10,2);
	select * from yueshu;

更改起始列的方法:手动添加一个想开始的id

	insert into yueshu values(10,'jack','男',1,10,2);

(2)修改表时添加标识列

	alter table yueshu modify column id int auto_increment;
	show index from yueshu;

六、TCL:transaction control language事务控制语言

1.事务

/*事务:一个或一组sql语句组成一个执行单元,这个执行单元要么全部执行,要么全部不执行,
当中间发生执行错误时发生回滚:即撤销已执行的语句
事务的ACID熟悉:
原子性(Atomicity):不可再分割,要么全部执行,要么全部不执行
一致性(Consistency):事务执行,事务必须从一个一致状态转换到另一个一致状态
隔离性(isolation):并发执行的事务不能相互干扰(受隔离级别影响)
持久性(Durability):事务执行后会永久的影响数据库

事务的创建:
隐式事务:事务没有明显的开始和结束的标记,比如insert、update、delete
显式事务:事务有明显的开始和结束的标记
必须设置事务自动提交功能为禁用
show variables like ‘autocommit’;
set autocommite=0;
步骤一:开启事务
set autocommite=0;
start transaction;-- 可选
步骤二:编写事务中的sql语句(select、update、insert、delete)
步骤三:结束事务
方法一:commit:提交
方法二:rollback:回滚
savepoint+节点名:设置保存点
*/

展示本数据库支持的引擎

	show engines;-- innoDB支持回滚,myisam、memory不支持回滚

演示事物的操作步骤

	use ch10;
	SET SQL_SAFE_UPDATES=0;-- 关闭安全模式
	set autocommit = 0;
	start transaction;
	update testinfo set name='slilank' where id=1;
	update testinfo set name='jack' where id=2;
	rollback;
	commit;
	select * from testinfo;
	show variables like 'updatemode'

delete和truncate在事物的使用时的区别

use ch10;
select * from copy;
insert into copy values(1,'张三的法外之旅',10.0,1,now());
SET SQL_SAFE_UPDATES=0;-- 关闭安全模式
-- delete 可以成功回滚
set autocommit = 0;
start transaction;
delete from copy;
rollback;
-- truncate 不支持回滚
set autocommit = 0;
start transaction;
truncate table copy;
rollback;

2.隔离级别

/*对于并发事务:
脏读:更新没有被提交
不可重复读:同一事物中更新了后再次读取的结果不同了
幻读:插入后如果事物再次读取同一个表会多出几行
设置隔离级别来避免以上并行事物执行的错误
事物的隔离级别:
脏读 不可重复读 幻读
read uncommitted o o o
read committed x o o Oracle默认级别
repeatable read x x o mysql默认级别
serializable x x x
*/

查看当前的隔离级别

	select @@tx_isolation;

设置隔离级别

	set transaction isolation level read committed;

savepoint应用演示

	use ch10;
	set autocommit = 0;
	start transaction;
	update testinfo set name='blue' where id=1 limit 2;
	savepoint a;
	update testinfo set name='jack' where id=2;
	rollback to a;

3.视图

/*含义:虚拟表,和普通表一样使用
mysql5.0.1刚添加的功能,通过表动态表动态生成的数据
创建语法的关键字 是否实际占用物理空间 使用
视图 create view 没有(只是保存了sql逻辑) 增删改查,一般不使用增删改
表 creat table 是 增删改查
*/

	select id,name from testinfo where name like '%e%'; 

创建视图

	create view v1 as
	select id,name from testinfo;
	select * from v1 where name like '%e%'; 

修改视图

#方式一:

	create or replace view v1 as
	select id,name from testinfo where id between 1 and 10; 

#方式二:

	alter view v1 as
	select * from testinfo where name like '%m%';

删除视图

	drop view v1;

查看视图结果

	desc v1;
	show create view v1;

– 含有group by关键词的视图不能更新,常量视图不能更新,select中包含子查询的不能更新,
– 带join的连接查询不能更新(能update但不能insert)
– from一个不能更新的视图的视图不能更新
– where子句的子查询引用了from子句中的表的视图不能更新

七、变量

/*
系统变量:
全局变量、会话变量
自定义变量:
用户变量、局部变量
*/

1.系统变量

说明:变量由系统提供,不是用户定义,属于服务器层面
使用的语法:

查看所有的系统变量

	show global variables;
	show session variables;

查看满足条件的部分系统变量

	show global variables like '%isolation%';

查看指定的某个系统变量

	select @@global.autocommit;
	select @@session.transaction_isolation;-- 默认seesion

为某个系统变量赋值

方式一:
set global/session 系统变量=‘值’;
方式二:
set @@global/session.系统变量=‘值’;

(1)全局变量:
#作用域:服务器每次启动将为所有的全局变量赋初始值,针对于所有的会话(连接)有效,但不能跨重启
#若需持久化更改全局变量需更改配置文件
(2)会话变量
#作用域:进阶针对于当前会话/连接有效

2.自定义变量

说明:变量是用户自定义的,不是由系统的
使用步骤:声明、赋值、使用

#1.用户变量:针对于当前会话/连接有效同于会话变量的作用域

声明并初始化、赋值

	set @str='aaa';
	set @x:=1;
	select @y:=2;

赋值方法二

	select max(id) into @y from testinfo; 

查看用户变量

	select @y;

#2.局部变量:仅在begin end中有效,在第一句的位置使用

声明

	declare '变量名' varchar;
	declare 'name' varchar default '小米';

赋值

	set name ='aaa';
	set name:='bbb';
	select @name:=null;
	select max(id) into @name from testinfo; 

查看

	select name;

八、存储过程和函数

/*
提高代码重用性
简化操作
减少了编译次数并且减少了和数据库服务器的连接次数,提高了效率
*/
#存储过程:可以有0,1,多个返回值一,组实现预编译好的sql语句的集合,理解成批处理语句
#函数:有且仅有一个返回值

1.存储过程创建语法和调用语法

/*参数模式:
in:传入值
out:可以作为返回值
inout:既可以作为输入又可以作为输出
存储过程中只有一条语句时begin end可以忽略
存储过程中每条语句必须以分号结尾
存储过程的结尾可以使用delimiter重新设置
语法:delimiter ¥;
*/

	use ch10;
	delimiter $
	
	create procedure function1(in id int,in stuname varchar(20))-- (参数模式,参数名,参数类型)
	begin
	insert into testinfo values(id,stuname)$
	end $
	
	create procedure function2(in id int,out oid int,out name varchar(20))
	begin
		select t.id,t.name into oid,name
	    from testinfo t
	    where t.id = id$
	end $
	call function1(12,"abaer") $
	call function2(2,@id,@name) $
	select @name $

2.删除存储过程

	drop procedure function1$

3.查看存储过程结构

	desc function1$

4.函数创建语法

	create function f1() returns int
	begin
		declare a default 0$
	    select count(*) into a 
	    from testinfo$
	    return a$
	end $

5.函数调用语法

	select f1() $

6.查看函数

	show create function f1;

7.删除函数

	drop function f1;

九、循环结构

#while、loop、repeat
#循环控制
#iterate类似于continue
#leave类似于break

案例:创建随机字符串

drop table if exists stringcontent;
create table stringcontent(
id int primary key auto_increment,
content varchar(20)
);
delimiter $
create procedure test_randstr_insert(in insertCount int)
begin
	declare i int default 1;
    declare str varchar(26) default 'abcdefghigklmnopqistuvwxyz';
    declare startIndex int default 1;
    declare len int default 1;
    while i < insetCount do
        set len = floor(rand()*(21-startIndex)+1);
        set startInddex = floor(rand()*26+1);
        insert into stringcontent values(substr(str,startIndex,len));
        set i = i + 1;
	end while;
end $

MySQL基础篇到此结束!!!大家辛苦了。
世上无难事,只怕有心人。
为了想去的远方,为了想见的那个优秀的人,加油!祝大家:

qaq

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值