3 SQL细说(超详细)

3 SQL细说(超详细)

细说SQL,由浅入深

建库

create database ceshi charset=utf8;
show create database ceshi;

创建数据表

drop table if exists students;
create table students ( studentNo varchar(10) primary key, name varchar(10), sex varchar(1), hometown varchar(20), age tinyint(4), class varchar(10), card varchar(20));

插入数据

insert into students values ('001', '王昭君', '女', '北京', '20', '1班', '340322199001247654'),('002', '诸葛亮', '男', '上海', '18', '2班', '340322199002242354'),('003', '张飞', '男', '南京', '24', '3班', '340322199003247654'),('004', '白起', '男', '安徽', '22', '4班', '340322199005247654'),('005', '大乔', '女', '天津', '19', '3班', '340322199004247654'),('006', '孙尚香', '女', '河北', '18', '1班', '340322199006247654'),('007', '百里玄策', '男', '山西', '20', '2班', '340322199007247654'),('008', '小乔', '女', '河南', '15', '3班', null),('009', '百里守约', '男', '湖南', '21', '1班', ''),('010', '妲己', '女', '广东', '26', '2班', '340322199607247654'),('011', '李白', '男', '北京', '30', '4班', '340322199005267754'),('012', '孙膑', '男', '新疆', '26', '3班', '340322199000297655');

查询所有字段

select * from 表名
select * from students;

3 SQL细说(超详细)

查询指定字段

select 列1,列2,… from 表名
select students.name,students.age from students;

3 SQL细说(超详细)

别名

在select后面的列名部分,可以使用空格或者as为列起别名,这个别名出现在结果集中
select s.name,s.age from students  s;

3 SQL细说(超详细)

类似于group by本身
select sex from students group by sex;

3 SQL细说(超详细)

消除重复行

在select后面列前使用distinct可以消除重复的行
select distinct sex from students;

3 SQL细说(超详细)

条件判断

基本概念
使用where子句对表中的数据筛选,符号条件的数据会出现在结果集中
select 字段1,字段2… from 表名 where 条件;
select * from students where studentNo=1;

3 SQL细说(超详细)

where后面支持多种运算符,进行条件的处理

比较运算
	比较运算符
		等于: =
		大于: >
		大于等于: >=
		小于: <
		小于等于: <=
		不等于: !=
	例:
		查询小乔的年龄
		select age from students where name='小乔';
		查询20岁以下的学生
		select * from students where age<20;
		查询家乡不在北京的学生
		select * from students where hometown!='北京';
逻辑运算
	and
		查询年龄小于20的女同学
		select * from students where age<20 and sex='女';
	or
		select * from students where sex='女' or class='1班';
	not
		select * from students where not hometown='天津';
模糊查询
	like
		%表示任意多个任意字符
			查询姓孙的学生
			select * from students where name like '孙%';
			查询叫乔的学生
			select * from students where name like '%乔';
			查询姓名含白的学生
			select * from students where name like '%白%';
			查询姓名为两个字的学生
			select * from students where name like '__';
		_表示一个任意字符 
			查询姓孙且名字是一个字的学生
			select * from students where name like '孙_';
范围查询
	in 表示在一个非连续的范围内
		查询家乡是北京或上海或广东的学生
		select * from students where hometown in ('北京','上海','广东');
	between ... and ...表示在一个连续的范围内
		查询年龄为18至20的学生
		select * from students where age between 18 and 20;
空判断
	空判断
		注意:null与''是不同的 判空is null
		查询没有填写身份证的学生
		select * from students where card is null;
	判非空
		select * from students where card is not null;

排序

为了方便查看数据,可以对数据进行排序
语法:将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推 默认按照列值从小到大排列
select * from 表名 order by 列1 asc|desc,列2 asc|desc,…
例子:
查询所有学生信息,按年龄从小到大排序
select * from students order by age;
查询所有学生信息,按年龄从大到小排序,年龄相同时,再按学号从小到大排序
select * from students order by age desc,studentNo;

聚合函数

为了快速得到统计数据,经常会用到如下5个聚合函数 
count(*)表示计算总行数,括号中写星与列名,结果是相同的 聚合函数不能在 where 中使用

3 SQL细说(超详细)
聚合函数不能在 where 中使用
查询学生总数
	select count(*) from students;
max(列)表示求此列的最大值 
	查询女生的最大年龄
	select max(age) from students where sex='女';
min(列)表示求此列的最小值 
	查询1班的最小年龄
	select min(age) from students;
avg(列)表示求此列的平均值 
	查询女生的平均年龄
	select avg(age) from students where sex='女';
sum(列)表示求此列的和 
	查询北京学生的年龄总
	select sum(age) from students where hometown='北京';

分组

按照字段分组,表示此字段相同的数据会被放到一个组中 分组后,分组的依据列会显示在结果集中,其他列不会显示在结果集中 可以对分组后的数据进行统计,做聚合运算
语法:select 列1,列2,聚合… from 表名 group by 列1,列2…
例:
查询各种性别的人数
select sex,count(*) from students group by sex;
查询各种年龄的人数
select age,count(*) from students group by age;
查询各个班级学生的平均年龄、最大年龄、最小年龄
select max(age),min(age),avg(age) from students group by class;

分组后的数据筛选

语法:
select 列1,列2,聚合... from 表名
 group by 列1,列2,列3... having 列1,...聚合...
having后面的条件运算符与where的相同
having和where的区别
where:
1、“Where”是一个约束声明,在查询数据库的结果返回之前对数据库中的查询条件进行约束,即在结果返回之前起作用(分组前)
2、where用在聚合函数之前,后面不能使用“聚合函数”
having:
1、“Having”是一个过滤声明,所谓过滤是在查询数据库的结果返回之后进行过滤,即在结果返回之后起作用(分组后)
2、having可以用在“聚合函数”之后,所以可以使用聚合函数
例:
查询男生总人数
方案一
select count(*) from students where sex='男';
方案二
select sex,count(*) from students group by sex having sex='男';

对比where与having
where是对from后面指定的表进行数据筛选,属于对原始数据的筛选 having是对group by的结果进行筛选,建议多用where更节省资源

mysql语句执行顺序

3 SQL细说(超详细)

获取部分行

当数据量过大时,在一页中查看数据是一件非常麻烦的事情
语法:
select * from 表名 limit start,count;
从start开始,获取count条数据,start索引从0开始
例:
查询前3行学生信息
select * from students limit 0,3;
查询第4到第6行学生信息
select * from students limit 3,3;

连接查询

简介
当查询结果的列来源于多张表时,需要将多张表连接成一个大的数据集,再选择合适的列返回

左连接查询:查询的结果为两个表匹配到的数据加左表特有的数据,对于右表中不存在的数据 使用null填充

3 SQL细说(超详细)

右连接查询:查询的结果为两个表匹配到的数据加右表特有的数据,对于左表中不存在的数据 使用null填充

3 SQL细说(超详细)

全连接:全连接是A表的所有行并上B表的所有行得出的结果集,一般用于垂直分表后再结合

3 SQL细说(超详细)
3 SQL细说(超详细)
3 SQL细说(超详细)

通过union 连接两条单独的select语句

3 SQL细说(超详细)

准备数据,继续之后的查询类型

drop table if exists courses;

create table courses (
courseNo int(10) unsigned primary key auto_increment, name varchar(10)
);
insert into courses values ('1', '数据库'),
('2', 'qtp'),
('3', 'linux'),
('4', '系统测试'),
('5', '单元测试'),
('6', '测试过程');
3 SQL细说(超详细)
drop table if exists scores; 
create table scores (
id int(10) unsigned primary key auto_increment, courseNo int(10),
studentno varchar(10), score tinyint(4)
);
insert into scores values ('1', '1', '001', '90'),
('2', '1', '002', '75'),
('3', '2', '002', '98'),
('4', '3', '001', '86'),
('5', '3', '003', '80'),
('6', '4', '004', '79'),
('7', '5', '005', '96'),
('8', '6', '006', '80');
3 SQL细说(超详细)

等值连接

方式一
select * from 表1,表2 where 表1.列=表2.列;

方式二(又称内连接)
select * from 表1
inner join 表2 on 表1.列=表2.

例子:

查询学生信息及学生的成绩

select
* from
students stu, scores sc
where
stu.studentNo = sc.studentNo;

select
* from
students stu
inner join scores sc on stu.studentNo = sc.studentNo;

查询课程信息及课程的成绩

select
* from
courses cs, scores sc
where
cs.courseNo = sc.courseNo;

select
* from
courses cs
inner join scores sc on cs.courseNo = sc.courseNo;

查询学生信息及学生的课程对应的成绩

select
* from
students stu, courses cs, scores sc
where
stu.studentNo = sc.studentno and cs.courseNo=sc.courseNo;

select
* from
students stu
inner join scores sc on stu.studentNo = sc.studentNo inner join courses cs on cs.courseNo = sc.courseNo;

查询王昭君的成绩,要求显示姓名、课程号、成绩

select
stu.name, sc.courseNo, sc.score
from
students stu, scores sc
where
stu.studentNo = sc.studentNo and stu.name = '王昭君';

select
stu.name, sc.courseNo, sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo where
stu.name = '王昭君';

查询王昭君的数据库成绩,要求显示姓名、课程名、成绩

select
stu.name, cs.name, sc.score
from
students stu, scores sc, courses cs
where
stu.studentNo = sc.studentNo and sc.courseNo = cs.courseNo and stu.name = '王昭君'
and cs.name = '数据库';

select
stu.name, cs.name, sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo inner join courses cs on sc.courseNo = cs.courseNo where
stu.name = '王昭君' and cs.name = '数据库';

查询所有学生的数据库成绩,要求显示姓名、课程名、成绩

select
stu.name, cs.name, sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo inner join courses cs on sc.courseNo = cs.courseNo where
cs.name = '数据库';

select
stu.name, cs.name, sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo inner join courses cs on sc.courseNo = cs.courseNo where
cs.name = '数据库';

查询男生中最高成绩,要求显示姓名、课程名、成绩

select
stu.name, cs.name, sc.score
from
students stu, scores sc, courses cs
where
stu.studentNo = sc.studentNo and sc.courseNo = cs.courseNo and stu.sex = '男'
order by
sc.score desc limit 1;

select
stu.name, cs.name, sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo inner join courses cs on sc.courseNo = cs.courseNo where
stu.sex = '男'
order by
sc.score desc limit 1;

左连接

格式
select * from 表1
left join 表2 on 表1.列=表2.列

例:查询所有学生的成绩,包括没有成绩的学生

select
* from
students stu
left join scores sc on stu.studentNo = sc.studentNo;

查询所有学生的成绩,包括没有成绩的学生,需要显示课程名

select
* from
students stu
left join scores sc on stu.studentNo = sc.studentNo left join courses cs on cs.courseNo = sc.courseNo;

右连接

格式
select * from 表1
right join 表2 on 表1.列=表2.列;

添加两门课程

insert into courses values 
(0, '语文'),
(0, '数学');


查询所有课程的成绩,包括没有成绩的课程

select
* from
scores sc
right join courses cs on cs.courseNo = sc.courseNo;

查询所有课程的成绩,包括没有成绩的课程,包括学生信息

select
* from
scores sc
right join courses cs on cs.courseNo = sc.courseNo left join students stu on stu.studentNo=sc.studentNo;

自关联

表结构:
设计省信息的表结构
provinces id,ptitle
设计市信息的表结构
citys id,ctitle ,proid
citys表的proid表示城市所属的省,对应着provinces表的id值
问题:能不能将两个表合成一张表呢? 思考:观察两张表发现,citys表比provinces表多一个列proid,其它列的类型都是一样的 意义:存储的都是地区信息,而且每种信息的数据量有限,没必要增加一个新表,或者将来还 要存储区、乡镇信息,都增加新表的开销太大

建表

定义表areas,结构如下
id atitle pid
因为省没有所属的省份,所以可以填写为null
城市所属的省份pid,填写省所对应的编号id 这就是自关联,表中的某一列,关联了这个表中的另外一列,但是它们的业务逻辑含义是不一 样的,城市信息的pid引用的是省信息的id 在这个表中,结构不变,可以添加区县、乡镇街道、村社区等信息

准备数据:
create table areas( aid int primary key, atitle varchar(20), pid int);

insert into areas
values ('130000', '河北省', NULL),
('130100', '石家庄市', '130000'),
('130400', '邯郸市', '130000'),
('130600', '保定市', '130000'),
('130700', '张家口市', '130000'),
('130800', '承德市', '130000'),
('410000', '河南省', NULL),
('410100', '郑州市', '410000'),
('410300', '洛阳市', '410000'),
('410500', '安阳市', '410000'),
('410700', '新乡市', '410000'),
('410800', '焦作市', '410000');
3 SQL细说(超详细)

例题:
查询一共有多少个省
select count(*) from areas where pid is null;

查询河南省的所有城市
子查询
select atitle from areas where atitle !="河南市" and pid=(select aid from areas where atitle="河南省");

连表查询
先进行连表
select * from areas a inner join areas b on a.aid=b.pid;

3 SQL细说(超详细)
select
* from
areas as p
inner join areas as c on c.pid=p.aid where
p.atitle='河北省';

或者
 select * from areas a,areas b where a.aid=b.pid and a.atitle="河南省";

添加区县数据

insert into areas values 
('410101', '中原区', '410100'),
('410102', '二七区', '410100'),
('410103', '金水区', '410100');

查询郑州市的所有区县

法一
select * from areas a,areas b where a.aid=b.pid and a.atitle="郑州市";

法二

select
* from
areas as c
inner join areas as a on a.pid=c.aid where
c.atitle='郑州市';

查询河南省的所有区县

法一
select * from areas a,areas b,areas c where a.aid=b.pid and b.aid=c.pid and a.atitle="河南省";

法二

select
* from
areas as p
left join areas as c on c.pid=p.aid left join areas as a on a.pid=c.aid where
p.atitle='河南省';

子查询

在一个 select 语句中,嵌入了另外一个 select 语句, 那么被嵌入的 select 语句称之为子查询语句

主查询:主要查询的对象,第一条 select 语句

主查询和子查询的关系
子查询是嵌入到主查询中 子查询是辅助主查询的,要么充当条件,要么充当数据源 子查询是可以独立存在的语句,是一条完整的 select 语句

子查询分类

就查询大于平均年龄的学生对子查询进行理解

3 SQL细说(超详细)

select * from students where age>(select avg(age) from students);

标量子查询: 子查询返回的结果是一个数据(一行一列) 
查询王昭君的成绩,要求显示成绩
select * from scores where studentno=(select studentno from students where name="王昭君");

列子查询: 返回的结果是一列(一列多行)
核心:使用 in查多行
查询18岁的学生的成绩
连表c查询(需要多表的结果时使用此方法)
select s.studentNo,name,score from students s,scores where s.studentNo=scores.studentno and age=18;
子查询(输出结果只在一个表中)
select score from scores where studentno in (select studentNo from students where age=18);

行子查询: 返回的结果是一行(一行多列) 
核心思想:多个字段同时约束
查询男生中年龄最大的学生信息
方法一
select * from students where age=(select max(age) from students where sex="男");
方法二
select * from students where (sex,age) = (select sex,age from students where sex='男' order by age desc limit 1);

表级子查询: 返回的结果是多行多列
in 后的括号写多个字段,只要与里面的约束项有交集即可
查询多个字段+in实现多行多列
select c.name,score from scores,courses c where c.courseNo=scores.courseNo and c.name in ('数据库','系统测试');

子查询中特定关键字使用
格式: 主查询 where 条件 in (列子查询)
any | some 任意一个
格式: 主查询 where 列 = any (列子查询)
在条件查询的结果中匹配任意一个即可,等价于 in
all
格式: 主查询 where 列 = all(列子查询) : 等于里面所有
格式: 主查询 where 列 <>all(列子查询) : 不等于其中所有
!=all 等价于 not in

数据分表

创建“商品分类”表
create table if not exists goods_cates(
cate_id int unsigned primary key auto_increment, cate_name varchar(40)
);

查询goods表的所有记录,并且按"类别"分组,然后将分组结果写入到goods_cates数据表中
insert into goods_cates (cate_name) select cate from goods group by cate;

通过goods_cates数据表来更新goods表
连表并复制过去(连表并设置)
update goods as g inner join goods_cates as c on g.cate = c.cate_name set cate = cate_id;

通过create…select来创建数据表并且同时写入记录,一步到位
create table goods_brands (
brand_id int unsigned primary key auto_increment,
brand_name varchar(40)) select brand_name from goods group by brand_name;
相当于两条语句中省略了分号

通过goods_brands数据表来更新goods数据表
update goods as g inner join goods_brands as b on g.brand_name = b.brand_name set g.brand_name = b.brand_id;

查看 goods 的数据表结构,会发现 cate 和 brand_name对应的类型为 varchar 但是存储的都 是字符串

修改数据表结构,把cate字段改为cate_id且类型为int unsigned,把brand_name字段改为 brand_id且类型为int unsigned分别在 good_scates 和 goods_brands表中插入记录
insert into goods_cates(cate_name) values ('路由器'),('交换机'),('网卡'); insert into goods_brands(brand_name) values ('海尔'),('清华同方'),('神舟');

在 goods 数据表中写入任意记录
insert into goods (name,cate_id,brand_id,price) values('LaserJet Pro P1606dn 黑白激光打印机','12','4','1849');

查询所有商品的详细信息 (通过左右链接来做)
select * from goods left join goods_cates on goods.cate_id=goods_cates.id inner join goods_brands on goods.brand_id=goods_brands.id;

示没有商品的品牌(通过右链接+子查询来做)
右链接
select * from goods right join goods_brands on goods.brand_id =goods_brands.id;
子查询
select * from goods_brands where id not in (select DISTINCT brand_id from goods);

内置函数

拼接字符串concat(str1,str2…)
演示
select concat(12,34,'ab');
案例
体现类似"王昭君的家乡是北京"的功能.

包含字符个数length(str)
演示
select length('abc');
案例:查找班级里边名字为两个字的所有学生信息

截取字符串
left(str,len)返回字符串str的左端len个字符 right(str,len)返回字符串str的右端len个字符 substring(str,pos,len)返回字符串str的位置pos起len个字符
演示
select substring('abc123',2,3);
案例:实现王昭君叫王某某,张飞叫张某某的功能

lpad(如果不够左边补齐),rpad(如果不够右边补齐)
lpad:函数语法:lpad(str1,length,str2)。其中str1是第一个字符串,length是结果字符串的长度,str2是一个填充字符串。如果str1的长度没有length那么长,则使用str2在左侧填充;如果str1的长度大于length,则截断。

例子:

3 SQL细说(超详细)
3 SQL细说(超详细)

去除空格
ltrim(str)返回删除了左空格的字符串str rtrim(str)返回删除了右空格的字符串str

演示

3 SQL细说(超详细)
3 SQL细说(超详细)

案例:实现左右空格都去掉的功能

3 SQL细说(超详细)

大小写转换

lower(str)
upper(str)
演示

3 SQL细说(超详细)

数学函数

求四舍五入值round(n,d),n表示原数,d表示小数位置,默认为0

3 SQL细说(超详细)

求x的y次幂pow(x,y)

3 SQL细说(超详细)

获取圆周率PI()

3 SQL细说(超详细)

随机数rand(),值为0-1.0的浮点数

3 SQL细说(超详细)

案例1:实现0-10之间的随机数
案例2:做出一个从学生中抽奖的功能

日期时间函数

当前日期
select current_date();

3 SQL细说(超详细)

当前时间
select current_time();

3 SQL细说(超详细)

当前日期时间
select now();

3 SQL细说(超详细)

日期格式化
date_format(date,format)
参数format可选值如下
%Y 获取年,返回完整年份
%y 获取年,返回简写年份
%m 获取月,返回月份
%d 获取日,返回天值
%H 获取时,返回24进制的小时数
%h 获取时,返回12进制的小时数
%i 获取分,返回分钟数
%s 获取秒,返回秒数

例:将使用-拼接的日期转换为使用空格拼接,年份改成简单版
select date_format('2016-12-21','%y %m %d');

3 SQL细说(超详细)

流程控制

case语法:等值判断 说明:当值等于某个比较值的时候,对应的结果会被返回;如果所有的比较值都不相等则返回 else的结果;如果没有else并且所有比较值都不相等则返回null

格式:case 值 when 比较值1 then 结果1 when 比较值2 then 结果2 … else 结果 end as result;

演示

3 SQL细说(超详细)

案例:做出一个女同学称为美女,男同学称为帅哥的小功能

自定义函数

创建

delimiter $$ (定义$$为分隔符)
create function 函数名称(参数列表) returns 返回类型
begin 
sql语句 
end
$$ 
delimiter ;(还原";"为分隔符)


delimiter $$ 定义了$$ 暂时取代“;”的作用,切记之后改回来
说明:delimiter用于设置分割符,默认为分号 在“sql语句”部分编写的语句需要以分号结尾,此时回车会直接执行,所以要创建存储过程前需 要指定其它符号作为分割符

示例
要求:创建函数my_trim,用于删除字符串左右两侧的空格

step1:定义分割符
delimiter $$

step2:创建函数

create function my_trim(str varchar(100)) returns varchar(100) begin 
return ltrim(rtrim(str)); 
end
$$
3 SQL细说(超详细)

step3:还原分割符
delimiter ;

使用自定义函数

select ' abc ',my_trim(' abc ');

3 SQL细说(超详细)

存储过程

存储过程,也翻译为存储程序,是一条或者多条SQL语句的集合

语法

delimiter //
create procedure 存储过程名称(参数列表) begin
sql语句
end
// 
delimiter ;

示例:
创建查询过程,查询学生信息
step1:设置分割符
delimiter //
step2:创建存储过程

create procedure proc_stu() 
begin
select * from students; 
end
//

step3:还原分割符
delimiter ;

调用
语法
call 存储过程(参数列表);
call proc_stu();

3 SQL细说(超详细)

视图

视图可以看作定义在数据库上的虚拟表,视图是由一张或多张表中的数据组成的,从数据库系统外部来看,视图就如同一张表一样,对表能够进行的一般操作都可以应用于视图

视图的作用:
视图隐藏了底层的表结构,简化了数据访问操作
加强了安全性,使用户只能看到视图所显示的数据

格式:定义视图,建议以v_开头
create view 视图名称 as select语句;
例:创建视图,查询学生对应的成绩信息

create view v_stu_score_course as select
stu.*,cs.courseNo,cs.name courseName,sc.score from
students stu
inner join scores sc on stu.studentNo = sc.studentNo inner join courses cs on cs.courseNo = sc.courseNo;

查看视图:查看表会将所有的视图也列出来
show tables;

3 SQL细说(超详细)

使用:视图的用途就是查询
select * from v_stu_score_course;

3 SQL细说(超详细)

删除视图
drop view 视图名称;
drop view v_stu_score_course;

事务

事务广泛的运用于订单系统、银行系统等多种场景,多个步骤要不全部执行,要不一条也不执行
事务主要用来处理操作两大,复杂度高的数据,Innodb存储引擎支持事务;MyISAM不支持事务

事务ACID特点
原子性(atomicity)
事务是一个整体,是不可分割的,事务中所有操作要不都执行,要不都不执行
一致性(consistency)
即当事务完成时,数据必须处于一致状态
在事务开始之前,数据处于一致状态,当事务开始后,数据可能处于不一致状态,事务执行完成后,数据处于一致状态。
隔离性(isolation)
对数据进行修改的所有并发事务都是隔离的,以防止多个事务执行时由于交叉执行导致数据不一致;
持久性(durability)
事务处理的结果都是永久的

案例
现在A要给B转账500元
1. 检查A的账户余额>500元
2. A 账户中扣除500元;
3. B 账户中增加500元;
A扣钱和B加钱,要么同时成功,要么同时失败。事务的需求就在于此 所谓事务,它是一个操作序列,这些操作要么都执行,要么都不执行,它是一个不可分割的工 作单位

要求:表的引擎类型必须是innodb类型才可以使用事务,这是mysql表的默认引擎 查看表的创建语句,可以看到engine=innodb

3 SQL细说(超详细)

方式
开启事务
开启事务后执行修改命令,变更会维护到本地缓存中,而不维护到物理表中
begin;
提交事务
将缓存中的数据变更维护到物理表中
commit;
回滚事务
放弃缓存中变更的数据
rollback;

实验:
开启两个终端
查询学生信息
select * from students;
终端1增加数据
begin;
insert into students(studentNo,name) values ('013','我是新来的');
select * from students;
此时终端2查询数据发现并没有插入新数据据
select * from students;
终端1提交数据
commit;
终端二查询,发现有新增的数据
select * from students;

设置自动提交
show variables like "autocommit";
set autocommit=0或1

索引

普通索引(看作一个字段)

是最基本的索引,它没有任何限制。

查看索引
show index from 表名\G

3 SQL细说(超详细)

创建索引(类似于字段的添加)
方式一:建表时创建索引

create table 
test_table(
id int primary key,
name varchar(10) unique, age int,
index index_age(age)
);

方式二:对于已经存在的表,添加索引
如果指定字段是很长的字符串,建议指定长度形成前缀索引(以前多少个字符做索引)
格式:建议的创建方式:create index 索引名称 on 表名(字段名称(长度))
或者是

3 SQL细说(超详细)

alter table students add index idx_studentNo(studentNo);

例:格式

3 SQL细说(超详细)

create index age_index on from(age);
create index name_index on from(name(10));

索引前缀
在创建索引时使用length指定该字段数据的前几个字符做索引,通常用于数据较长时

删除索引:
drop index 索引名称 on 表名;

3 SQL细说(超详细)

唯一性索引

与前面的普通索引类似,不同的就是:索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。

create unique index uk_sNo on students(studentNo);
show index from students\G;

3 SQL细说(超详细)

主键索引

是一种特殊的唯一索引,一个表只能有一个主键,不允许有空值。一般是在建表的时候同时创建主键索引

不需要指定名称:alter table students add primary key(studentNo);
show keys from students;
删除主键
alter table students drop primary key;

全文索引

主要用来查找文本中的关键字,而不是直接与索引中的值相比较。

fulltext索引跟其它索引大不相同,它更像是一个搜索引擎,而不是简单的where语句的参数匹配。fulltext索引配合match against操作使用,而不是一般的where语句加like。它可以在create table,alter table ,create index使用,不过目前只有char、varchar,text 列上可以创建全文索引。

索引失效:
多条件中有or(如果条件1和条件2有一个没创建索引,都要进行全表扫描,索引失效)
使用like加%模糊查询
索引是表达式的一部分,或者加入判断和计算
字段类型是字符串,数据没有加‘’

索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。

索引总结
索引扫描方式是全表扫描。对于经常更新的数据的表或者数据较少的表,不建议使用索引
字段中唯一性比较差,不适合创建索引
所以应尽量建立在字段中数据较短的字段,如果数据比较长,应该创建前缀索引
创建索引的字段经常会在where中使用

索引缺点:

1.虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行insert、update和delete。因为更新表时,不仅要保存数据,还要保存一下索引文件。
2.建立索引会占用磁盘空间的索引文件。一般情况这个问题不太严重,但如果你在一个大表上创建了多种组合索引,索引文件的会增长很快。
索引只是提高效率的一个因素,如果有大数据量的表,就需要花时间研究建立最优秀的索引,或优化查询语句。

外键foreign key

如果一个实体的某个字段指向另一个实体的主键,就称为外键。被指向的实体,称之为主实体(主表),也叫父实体(父表)。负责指向的实体,称之为从实体(从表),也叫子实体(子表)
对关系字段进行约束,当为从表中的关系字段填写值时,会到关联的主表中查询此值是否存 在,如果存在则填写成功,如果不存在则填写失败并报错
查看外键
show create table 表名;

设置外键约束
方式一:创建数据表的时候设置外键约束

3 SQL细说(超详细)

方式二:对于已经存在的数据表设置外键约束
alter table 从表名 add foreign key (从表字段) references 主表名(主表字段);
删除外键:alter table 表名 drop foreign key 外键名称;
在实际开发中,很少会使用到外键约束,会极大的降低表更新的效率

字符编码

发展历程
ASCII:基本字符集使用128个常用字符,扩展字符集128个,共256个,用1个字节8位表示。
GB2312:中国国家标准的简体中文字符集,采用2个字节表示
GBK:1万多个汉字,采用2个字节表示
Unicode:两字节表示的世界通用码,它为每种语言中的每个字符设定了统一并且唯一的二进制编码
UTF-8:一种以8个bit为一组的Unicode的表示格式,是一种变长的编码方式,一个中文字符占3个字节
UTF-16:2或4个字节,固定长度

mysql中的字符编码
mysql5.7之前默认使用latinl,8.0开始默认使用utf8mb4

查看表的字符编码:
create table student(id int,name char(10));
show create table student;

3 SQL细说(超详细)

默认是拉丁

创建表时指定
create table class(id int,name char(10)) charset=utf8;
show create table class;

3 SQL细说(超详细)

查看字符编码变量
show variables like "character%";

3 SQL细说(超详细)

修改字符编码
1、编译时修改
2、之后配置文件修改
vim /etc/my.cnf
[mysqld]下加入
character-set-server=utf8

3 SQL细说(超详细)

重启服务
systemctl restart mariadb
再次进入,成功修改

3 SQL细说(超详细)

如果想要修改某个库的字符编码:
create database abc charset=utf8;
show create database abc;

3 SQL细说(超详细)

字符集校验

3 SQL细说(超详细)

系统相应修改字符集
ci:不区分大小写
cs:区分大小写
bin:区分大小写

存储引擎

查看存储引擎
查看所有存储引擎
show engines\G

查看默认存储引擎
show variables like "default_storage_engine";

3 SQL细说(超详细)

查看表的存储引擎
show create table student\G

3 SQL细说(超详细)

创建表时设定存储引擎:
create table 表名 (字段1 字段类型,字段2 字段类型,…)engine="存储引擎类型";

常见的存储引擎
Innodb

简介
	支持事务
	行级锁,每一条数据都可以锁定
	存储级别最大支持64TB
Inodb存储文件
	ibdatal:数据文件
	.frm:表结构
适用范围
	以写为主,对数据一致性比较高,支持事务、行级锁和外键约束

MyISAM

简介
	不支持事务
	表级锁
	存储级别最大支持256TB
MySAM存储引擎表存储三个文件:
	.frm 存储表格式
	.MYD 存储数据
	.MYI 存储引擎
适用范围
	以读为主,不频繁更新,插入和查询速度块,对数据一致性要求不高

MEMORY
工作在内存中,速度快、不能永久保存

查看帮助

?+数据类型

3 SQL细说(超详细)
3 SQL细说(超详细)

发布者:LJH,转发请注明出处:https://www.ljh.cool/6259.html

(0)
上一篇 2020年5月27日 下午1:04
下一篇 2020年5月29日 下午6:18

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注