1、SQL介绍 ***
结构化查询语言。5.7 以后符合SQL92标准的严格模式。通过sql_mode来控制
SQL分类 ***
DDL:数据定义语言
DCL:数据控制语言
DML:数据操作语言
DQL:数据的查询语言
3、数据类型、表属性、字符集 ***
3.1 数据类型
3.1.1 作用
保证数据的准确性和标准性。
3.1.2 种类
数值类型
tinyint : -128~127
int :-2^31~2^31-1
说明:手机号是无法存储到int的。一般是使用char类型来存储收集号
字符类型
char(11) :定长的字符串类型,在存储字符串时,最大字符长度11个,立即分配11个字符长度的存储空间,如果存不满,空格填充。
varchar(11):变长的字符串类型看,最大字符长度11个。在存储字符串时,自动判断字符长度,按需分配存储空间。
enum('bj','tj','sh'):枚举类型,比较适合于将来此列的值是固定范围内的特点,可以使用enum可以很大程度的优化我们的索引结构。
时间类型
DATETIME 范围为从 1000-01-01 00:00:00.000000 至 9999-12-31 23:59:59.999999。
TIMESTAMP 1970-01-01 00:00:00.000000 至 2038-01-19 03:14:07.999999。
timestamp会受到时区的影响二进制类型
3.2 表属性
3.2.1 列属性
约束
primary key :
主键约束设置为主键的列,此列的值必须非空且唯一,主键在一个表中只能有一个,但是可以有多个列一起构成。
not null
非空约束列值不能为空,也是表设计的规范,尽可能将所有的列设置为非空。可以设置默认值为0
unique key
唯一键列值不能重复
unsigned
无符号针对数字列,非负数。其他属性
key
索引可以在某列上建立索引,来优化查询
default
默认值列中,没有录入值时,会自动使用default的值填充
auto_increment
自增长针对数字列,顺序的自动填充数据(默认是从1开始,将来可以设定起始点和偏移量)
comment
注释
=======================================================
3.2.2 表的属性
存储引擎:InnoDB(默认的)
字符集和排序规则
utf8
utf8mb4
3.3 字符集和校对规则
3.3.1 字符集
utf8 utf8mb4
3.3.2 校对规则(排序规则)
大小写是否敏感
4、DDL应用 ****
4.1 数据定义语言
4.2 库定义
4.2.1 创建
create database / create schema
mysql> create database xuexiao;
建库规范:
1.库名不能有大写字母 *****
2.建库要加字符集 *****
3.库名不能有数字开头
4. 库名要和业务相关建库标准语句
mysql> create database db charset utf8mb4;
mysql> show create database xuexiao
4.2.2 删除(生产中禁止使用)
mysql> drop database oldboy;
4.2.3 修改
mysql> show create database xuexiao;
mysql> alter database xuexiao charset utf8mb4;
mysql> show create database xuexiao;
注意:修改字符集,修改后的字符集一定是原字符集的严格超集
mysql> show charset;mysql> show collation;
4.2.4 查询库相关信息(DQL)
show databases;
show create database oldboy;
4.3 表定义
4.3.1 创建
create table xuesheng (列1 属性(数据类型、约束、其他属性) ,列2 属性,列3 属性)
建表举例:
USE xuexiaoSELECT DATABASE();
CREATE TABLE xuesheng (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT COMMENT '学生学号',
sname VARCHAR(64) NOT NULL COMMENT '学生姓名',
xingbie ENUM('m','f','n') NOT NULL DEFAULT 'n' COMMENT '学生性别',
shouji CHAR(11) UNIQUE KEY NOT NULL COMMENT '手机号',
age TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '学生年龄',
ruxue TIMESTAMP NOT NULL DEFAULT NOW() COMMENT '入学时间'
)ENGINE=INNODB CHARSET=utf8mb4;
建表规范:
1. 表名小写
2. 不能是数字开头
3. 注意字符集和存储引擎
4. 表名和业务有关
5. 选择合适的数据类型
6. 每个列都要有注释
7. 每个列设置为非空,无法保证非空,用0来填充。
4.3.2 删除(生产中禁用次命令)
drop table t1;
4.3.3 修改
-- 1. 在xuesheng表中添加qq列
ALTER TABLE xuesheng ADD qq VARCHAR(64) UNIQUE KEY NOT NULL COMMENT 'qq号';
DESC xuesheng;
-- 2. 在sname后加微信列
ALTER TABLE xuexiao.xuesheng ADD weixin VARCHAR(64) UNIQUE KEY NOT NULL COMMENT '微信' AFTER sname;
DESC xuesheng;
-- 3. 在id列前加一个新列
numALTER TABLE xuesheng ADD num INT FIRST;
-- 4. 把刚才添加的列都删掉ALTER TABLE xuesheng DROP num;
ALTER TABLE xuesheng DROP weixin;
ALTER TABLE xuesheng DROP qq;
-- 5. 修改sname数据类型的属性
ALTER TABLE xuesheng MODIFY sname VARCHAR(32) NOT NULL COMMENT 'aa';DESC xuesheng;
-- 6. 将sname 改为sn 数据类型改为 varchar(64)ALTER TABLE xuesheng CHANGE sname sn VARCHAR(64);
4.3.4 表属性查询(DQL)
use xuexiao show tables;
desc xuesheng;show create table xuesheng;
select * from xuesheng where id <5create table ceshi like xuesheng; (复制结构一样的空表)
5、DCL应用 ****
grant
revoke
6、DML应用 ***
6.1 作用
对表中的数据行进行增、删、改
6.2 insert
-- 1. 在学生表插入一行数据
DESC xuesheng;INSERT INTO xuesheng(sn,xingbie,shouji,age)
VALUES('zs','m', '110' ,18);
SELECT * FROM xuesheng;
-- 省事的插入方法
INSERT INTO xueshengVALUES(2,'ls','f','190',18,NOW());
SELECT * FROM xuesheng;
-- 2. 一次性录入多行数据
INSERT INTO xuesheng(sn,xingbie,shouji,age)VALUES('w5','f','120',19),('m6','m','119',20),('m66','f','1190',27);
SELECT * FROM xuesheng;
INSERT INTO xuesheng(sn,shouji,age)VALUES('w55','1200',17);
6.3 update
UPDATE xuesheng SET sn='zhao4' WHERE id=7;
注意:update语句必须要加where。
6.4 delete(危险!!)
delete from xuesheng where id=7;
伪删除:用update来替代delete,最终保证业务中查不到(select)即可
- 添加状态列
Master [xuexiao]>alter table xuesheng add state tinyint not null default 1;
- 使用update替代delete
Master [xuexiao]>update xuesheng set state=0 where id=6;Master [xuexiao]>select * from xuesheng;
- 业务查询时 ,加入状态判断
Master [xuexiao]>select * from xuesheng where state=1;
7、DQL应用(select ) *****
7.0
select 单独使用的情况查看mysql的参数设定情况:
Master [xuexiao]>select @@basedir;
Master [xuexiao]>select @@innodb_flush_log_at_trx_commit;
调用mysql的内置函数:
Master [world]>select database();
Master [(none)]>select user();
Master [(none)]>select now();
Master [xuexiao]>select concat("lisi shi ge da hun dan ");
7.1 from 子句语法:
select 列1,列2 from 表select * from 表;
例子:
oldguo带大家学单词:
world ===>世界
city ===>城市
country ===>国家
countrylanguage ===>国家语言
city ===>城市
DESC city;
ID :城市ID
NAME :城市名
CountryCode :国家代码,比如中国CHN 美国USA
District :区域
Population :人口
7.1.1 查询表中所有的数据(生产中避免使用)
SELECT * FROM city;
7.1.2 查询某些列的数据
SELECT NAME,population FROM world.city;
7.2 where
-- 1. 查询中国所有的城市
DESC city;SELECT * FROM city WHERE countrycode='CHN';
-- 2. 查询CH开头国家代号的城市信息
SELECT * FROM city WHERE countrycode LIKE 'CH%';
注意:%不能加在前面,例如:'%CH%'
-- 3. 查看中国和美国的城市信息
SELECT * FROM city WHERE countrycode='CHN' OR countrycode='USA';
或者:
SELECT * FROM city WHERE countrycode IN ('CHN','USA');
或者:
SELECT * FROM city WHERE countrycode='CHN'UNION ALLSELECT * FROM city WHERE countrycode='USA'
注意: 一般我们会将 or或者in 语句改写成union union all 语句
-- 4. 查询中国城市中人口数量大于500w的城市信息
SELECT * FROM city WHERE countrycode='CHN' AND population>5000000;
-- 5. 查询中国城市中人口数量小于9w的信息
SELECT * FROM city WHERE countrycode='CHN' AND population <90000;
-- 6. 查询一下世界上小于100人口的城市
SELECT * FROM city WHERE population<100;
-- 7. 查询人口数100w到200w之前的城市信息
SELECT * FROM city WHERE population>1000000 AND population <2000000
或者:
SELECT * FROM city WHERE population BETWEEN 1000000 AND 2000000;
7.3 group by +常用聚合函数
7.3.1 作用
根据 by后面的条件进行分组,方便统计,by后面跟一个列或多个列
7.3.2 常用聚合函数
max() :最大值
min() :最小值
avg() :平均值
sum() :总和
count() :个数
7.3.3 GROUP BY + 聚合函数公式
1.遇到统计想函数
2.形容词前 GROUP BY
3.函数中央是名词
4.列名select后添加
7.3.4 例子:
例子1:统计世界上每个国家的总人口数.
USE worldSELECT countrycode ,SUM(population) FROM city GROUP BY countrycode;
例子2: 统计中国各个省的总人口数量(练习)
SELECT district,SUM(Population) FROM city WHERE countrycode='chn' GROUP BY district;
例子3:统计世界上每个国家的城市数量(练习)
SELECT countrycode,COUNT(id) FROM city GROUP BY countrycode;
7.4 havingwhere|group|having
例子4:统计中国每个省的总人口数,将总人口数小于100w
SELECT district,SUM(Population)
FROM cityWHERE countrycode='chn'
GROUP BY district
HAVING SUM(Population) < 1000000 ;
例子5:统计中国各个省的平均人口数,显示结果是大于平均人口数的城市信息(练习)
SELECT city.district,AVG(city.population),
city.NAME,city.population
FROM city
WHEREcity.countrycode='chn'
GROUP BY city.district
HAVINGcity.population>AVG(city.population);
细节:
1. 在having时 ,如果说需要原表数据和统计后的值进行比较时,需要在调用列的时候加全表名或者别名
2. sql_mode=only_full_group_by参数的意思是:在select 后的查询列,必须是在group by出现过的列,或者使用函数括起来的。否则group by语句会报错
解决方案:
1.setsql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
2. 在问题列上加any_value(列名)
SELECTcity.district ,AVG(city.population) AS avp ,
any_value(city.NAME) AS avn ,
any_value(city.population) AS av
FROM city
WHERE city.countrycode='chn'
GROUP BY city.districtHAVING av >avp;
7.5 别名select user,host from mysql.user;
7.5.1 列别名
SELECT city.district ,
AVG(city.population) AS avp ,
any_value(city.NAME) AS avn,
any_value(city.population) AS av
FROM city
WHERE city.countrycode='chn'
GROUP BY city.district
HAVING any_value(city.population) >avp;
7.5.2 表别名对表的名字进行简化,主要在多表链接查询中应用较广泛例如:
select a.user,a.host from mysql.user as a;
group by + 函数 + having
7.5 order by + limit
7.5.1 作用实现先排序,by后添加条件列
7.5.2 应用案例
- 查看中国所有的城市,并按人口数进行排序(从大到小)
SELECT * FROM city
WHERE countrycode='CHN'
ORDER BY population DESC;
``
2. 统计中国各个省的总人口数量,按照总人口从大到小排序
SELECT district AS 省 ,
SUM(Population) AS 总人口
FROM city
WHERE countrycode='chn'
GROUP BY district
ORDER BY 总人口 DESC ;
- 统计中国各个省的总人口数量,按照总人口从大到小排序,只取6-10
SELECT district AS 省 ,
SUM(Population) AS 总人口
FROM city
WHERE countrycode='chn'
GROUP BY district
ORDER BY 总人口 DESC
LIMIT 5 , 5 ;
或者:
SELECT district AS 省 ,
SUM(Population) AS 总人口
FROM city
WHERE countrycode='chn'
GROUP BY district
ORDER BY 总人口 DESC
LIMIT 5 OFFSET 5 ;
SELECT district AS 省 ,
SUM(Population) AS 总人口
FROM city
WHERE countrycode='chn'
GROUP BY district
ORDER BY 总人口 DESCLIMIT 2 , 5 ;
SELECT district AS 省 ,
SUM(Population) AS 总人口
FROM city
WHERE countrycode='chn'
GROUP BY districtORDER BY 总人口
DESCLIMIT 10 ;
SELECT district AS 省 ,
SUM(Population) AS 总人口
FROM city
WHERE countrycode='chn
'GROUP BY district
ORDER BY 总人口
DESCLIMIT 5 OFFSET 2 ;
7.6 distinct:去重复
SELECT countrycode FROM city ;
SELECT DISTINCT(countrycode) FROM city ;
==============
7.7 join 多表连接查询
7.7.1 语法
查询张三的家庭住址
SELECT A.name,B.address FROM
A JOIN B
ON A.id=B.id
WHERE A.name='zhangsan'
7.7.2 例子:
-- 1. 查询一下世界上人口数量小于100人的城市名和国家名
SELECT b.name ,a.name ,a.population
FROM city AS a
JOIN country AS b
ON b.code=a.countrycode
WHERE a.Population<100
-- 2. 查询城市shenyang,城市人口,所在国家名(name)及国土面积(SurfaceArea)
SELECT a.name,a.population,b.name ,b.SurfaceArea
FROM city AS a
JOIN country AS b
ON a.countrycode=b.code
WHERE a.name='shenyang';
7.7.3 多表连接公式
1.数据来自多张表,优先想到多表连接join ON
2.关联表写join两端
3.on条件写两表的关联列
4.所有查询条件select后,注意表名和别名
5.where过滤条件写最后
7.7.4 项目需求:
学校库:school
student :学生表
sno: 学号
sname:学生姓名
sage: 学生年龄
ssex: 学生性别
=================
teacher :教师表
====
course :课程表
cno: 课程编号
cname:课程名字
tno: 教师编号
==================
score :成绩表
sno: 学号
cno: 课程编号
score:成绩
==================
-- 项目构建
CREATE DATABASE school CHARSET utf8;
USE school
CREATE TABLE student(
sno INT NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '学号',
sname VARCHAR(20) NOT NULL COMMENT '姓名',
sage TINYINT UNSIGNED NOT NULL COMMENT '年龄',
ssex ENUM('f','m') NOT NULL DEFAULT 'm' COMMENT '性别'
)ENGINE=INNODB CHARSET=utf8;
CREATE TABLE course(
cno INT NOT NULL PRIMARY KEY COMMENT '课程编号',
cname VARCHAR(20) NOT NULL COMMENT '课程名字',
tno INT NOT NULL COMMENT '教师编号'
)ENGINE=INNODB CHARSET utf8;
CREATE TABLE sc (
sno INT NOT NULL COMMENT '学号',
cno INT NOT NULL COMMENT '课程编号',
score INT NOT NULL DEFAULT 0 COMMENT '成绩'
)ENGINE=INNODB CHARSET=utf8;
CREATE TABLE teacher(
tno INT NOT NULL PRIMARY KEY COMMENT '教师编号',
tname VARCHAR(20) NOT NULL COMMENT '教师名字',
)ENGINE=INNODBCHARSETutf8;
============================================
INSERT INTO student(sno,sname,sage,ssex)
VALUES (1,'zhang3',18,'m');
INSERT INTO student(sno,sname,sage,ssex)
VALUES(2,'zhang4',18,'m'),
(3,'li4',18,'m'),
(4,'wang5',19,'f');
INSERT INTO student
VALUES(5,'zh4',18,'m'),
(6,'zhao4',18,'m'),
(7,'ma6',19,'f');
INSERT INTO student(sname,sage,ssex)
VALUES('oldboy',20,'m'),
'oldgirl',20,'f'),('oldp',25,'m');
===============================================
INSERT INTO teacher(tno,tname)
VALUES(101,'oldboy'),
(102,'hesw'),
(103,'oldguo');
DESC course;
INSERT INTO course(cno,cname,tno)
VALUES(1001,'linux',101),
(1002,'python',102),
(1003,'mysql',103);
DESC sc;
==============================
INSERT INTO sc(sno,cno,score)
VALUES(1,1001,80),
(1,1002,59),
(2,1002,90),
(2,1003,100),
(3,1001,99),
(3,1003,40),
(4,1001,79),
(4,1002,61),
(4,1003,99),
(5,1003,40),
(6,1001,89),
(6,1003,77),
(7,1001,67),
(7,1003,82),
(8,1001,70),
(9,1003,80),
(10,1003,96);
==================================
SELECT * FROM student;
SELECT * FROM teacher;
SELECT * FROM course;
SELECT * FROM sc;
===================================
student:
teacher:
teacher:
course:
sc:
========================
SQL练习题
- 统计zhang3,学习了几门课
SELECT st.sname ,
COUNT(sc.cno)
FROM student AS st
JOINscON st.sno=sc.sno
WHERE st.sname='zhang3'2.
查询zhang3,学习的课程名称有哪些?
SELECT st.sname ,
GROUP_CONCAT(co.cname)
FROM student AS st
JOIN scON st.sno=sc.sno
JOIN course AS co
ON sc.cno=co.cno
WHERE st.sname='zhang3'
- 查询oldguo老师教的学生名.
SELECT te.tname ,
GROUP_CONCAT(st.sname)
FROM student AS st
JOIN sc
ON st.sno=sc.sno
JOIN course AS co
ON sc.cno=co.cno
JOIN teacher AS te
ON co.tno=te.tno
WHERE te.tname='oldguo';
- 查询oldguo所教课程的平均分数
SELECT te.tname,
AVG(sc.score)
FROM teacher AS te
JOIN course AS co
ON te.tno=co.tno
JOIN sc
ON co.cno=sc.cno
WHERE te.tname='oldguo';
4.1 每位老师所教课程的平均分,并按平均分排序
SELECT te.tname,
AVG(sc.score)
FROM teacher AS te
JOIN course AS co
ON te.tno=co.tno
JOIN sc
ON co.cno=sc.cno
GROUP BY te.tname
ORDER BY AVG(sc.score) DESC ;
- 查询oldguo所教的不及格的学生姓名
SELECT te.tname,st.sname,sc.score
FROM teacher AS te
JOIN course AS co
ON te.tno=co.tno
JOIN sc
ON co.cno=sc.cno
JOIN student AS st
ON sc.sno=st.sno
WHERE te.tname='oldguo'
AND sc.score<60;
5.1 查询所有老师所教学生不及格的信息
SELECT te.tname,st.sname,sc.scoreFROM teacher AS teJOIN course AS coON te.tno=co.tnoJOIN scON co.cno=sc.cnoJOIN student AS stON sc.sno=st.snoWHERE sc.score<60;
7.8 union[all]主要用来优化 in 和 or 语句
SELECT * FROM city WHERE countrycode='CHN'UNION ALLSELECT * FROM city WHERE countrycode='USA'
7.9 子查询 **
-- 查询人口少于100人的城市所在的国家名字
select name,population,countrycode from city where population <100;A,B,CAAA BBB CCCselect name from country where code in (select countrycode from city where population <100;)
优化思路:
1.改写为join
2.利用临时表
8、information_schema.tables视图
DESC information_schema.
TABLESTABLE_SCHEMA ---->库名
TABLE_NAME ---->表名
ENGINE ---->引擎
TABLE_ROWS ---->表的行数
AVG_ROW_LENGTH ---->表中行的平均行(字节)
INDEX_LENGTH ---->索引的占用空间大小(字节)
-- 1. 查询整个数据库中所有库和所对应的表信息
SELECT table_schema,GROUP_CONCAT(table_name)FROM information_schema.tablesGROUP BY table_schema;
-- 2. 统计所有库下的表个数
SELECT table_schema,COUNT(table_name)FROM information_schema.TABLESGROUP BY table_schema
-- 3. 查询所有innodb引擎的表及所在的库
SELECT table_schema,table_name,ENGINE
FROM information_schema.`TABLES`
WHERE ENGINE='innodb';
-- 4. 统计world数据库下每张表的磁盘空间占用
SELECTtable_name,CONCAT((TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024," KB") AS size_KB
FROM information_schema.tables
WHERE TABLE_SCHEMA='world';
-- 5. 统计所有数据库的总的磁盘空间占用
SELECTTABLE_SCHEMA,CONCAT(SUM(TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024," KB") AS Total_KB
FROM information_schema.tables
GROUP BY table_schema;
mysql -uroot -p123 -e
"SELECT TABLE_SCHEMA,CONCAT(SUM(TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024,' KB') AS Total_KB
FROM information_schema.tables
GROUP BY table_schema;"
-- 6. 生成整个数据库下的所有表的单独备份语句模板语句:
mysqldump -uroot -p123 world city >/tmp/world_city.sql
SELECT CONCAT("mysqldump -uroot -p123 ",table_schema," ",table_name," >/tmp/",table_schema,"_",table_name,".sql" )
FROM information_schema.tables
WHERE table_schema NOT IN('information_schema','performance_schema','sys')
INTO OUTFILE '/tmp/bak.sh' ;
CONCAT("mysqldump -uroot -p123 ",table_schema," ",table_name," >/tmp/",table_schema,"_",table_name,".sql" )
-- 7. 107张表,都需要执行以下2条语句
ALTER TABLE world.city DISCARD TABLESPACE;
ALTER TABLE world.city IMPORT TABLESPACE;
SELECT CONCAT("alter table ",table_schema,".",table_name," discard tablespace")
FROM information_schema.tables
WHERE table_schema='world'
INTO OUTFILE '/tmp/dis.sql';
9、show 命令 ***
how databases; #查看所有数据库
show tables; #查看当前库的所有表SHOW TABLES FROM #查看某个指定库下的表show create database world #查看建库语句
show create table world.city #查看建表语句
show grants for root@'localhost' #查看用户的权限信息
show charset; #查看字符集
show collation #查看校对规则
show processlist; #查看数据库连接情况
show index from #表的索引情况
show status #数据库状态查看
SHOW STATUS LIKE '%lock%'; #模糊查询数据库某些状态
SHOW VARIABLES #查看所有配置信息
SHOW variables LIKE '%lock%'; #查看部分配置信息
show engines #查看支持的所有的存储引擎
show engine innodb status\G #查看InnoDB引擎相关的状态信息show binary logs #列举所有的二进制日志
show master status #查看数据库的日志位置信息show binlog evnets in #查看二进制日志事件
show slave status \G #查看从库状态
desc (show colums from city) #查看表的列定义信息