1、SQL介绍
结构化查询语言
5.7 以后符合SQL92 严格模式
通过sql_mode 参数来控制
2、常用SQL分类
DDL:数据定义语言
DML:数据操作语言
DCL:数据控制语言
DQL:数据查询语言
3、数据类型、表属性、字符集
3.1 数据类型
3.1.1 数据类型
int: -2^31 - 2^31
说明: 手机号是无法存储到int的。一般是使用char 类型来存储手机号或QQ号。
说明
数据类型
列值不能为空,也是表设计的规范,尽可能将所有的列设置为非空。可以设置默认值为0.
unique key: 唯一键
列值不能重复
unsigned: 无符号
针对数字列、非负数
启动属性
key: 索引
可以在某列上建立索引,来优化查询
3.2 表属性
3.2.1 列属性
约束:
primary key
not null
unique key
unsigned:无符号
default
auto_increment
comment
表的属性:
Innodb
字符集和排序规则
utf8
utf8mb4
校队规则(排序规则)
小大写是否敏感(以bin结尾的校队规则是区分大小写的)
4、DDL应用
4.1 数据定义语言
4.1.1 创建数据库
create database school;
create schema sch;
show scharset;
show collation'
create database test charset utf8;
create database xyz charset utf8mb4 collate utf8mb4_bin;(区分大小写)
create data db charset utf8mb4;
show create database xuexiao;
4.2.2 删除(生产中禁止使用)
drop database school;
4.2.3 修改
show create database school;
alter database school charset utf8;
注意:修改字符集,修改后的字符集一定是员字符集的严格超集(修改之后的字符集一定包含修改之前的字符集)
4.3 表定义
4.3.1 创建表
create table student (
id int not null primary key auto_increment comment '学号’,
sname varchar(50) not null comment '姓名‘,
age tinyint unsigned not null default 0 comment '年龄',
sgender enum('m','f','n'),
sfz char(18) not null unique comment '身份证',
intime datetime not null default now() comment '入学时间'
) engine=innodb charset=utf8mb4 comment '学生表';
交表规范:
1、表明小写
2、不能是数字开头
3、注意字符集和存储引擎
4、表名和业务有关
5、选择合适的数据类型
6、每个列都要有注释
7、每个列设置为非空、无法保证非空,用0来填充
4.3.3 删除(生产中禁用)
drop table t1;
4.3.4 修改
desc student;
alter table student add qq varchar(20) not null unique comment 'QQ';
2、在sname 后面加微信号
alter table studnet add wechat varchar(20) not null unique comment '微信号' after sname;
3、在id 列前加一个新列num;
alter table student add num int not null default 0 comment '数字' frist;
desc student;
4、把刚才添加的列都删除(这属于危险操作)
alter table student drop num;
alter table student drop qq;
5、修改sname 数据类型的熟悉
alter table student modify sname varchar(120) not null;
6、将sgender 改为sg 数据类型改为char 类型
alter talbe student change sgender sg char(2) not null default 'n';
desc student;
4.3 表属性查询(DQL)
use school
show tables;
desc student;
show create table student;
create table ceshi like stu;
5、DCL
grant
revoke
6 DML
作用: 对表中的数据行进行增删改
6.1 insert
insert into student(id,name,sage,sg,sfz,intime)
values
(1,'zs',18,'m','123456',now()),
(2,'sk',18,'f','1234567',now());
6.2 update
update student set sname='zhaowei' where id=2;
注意: update 语句必须要加where。
6.3 delete (危险!!!)如何真的也必须添加where条件限制
delete from student where id=3;
全表删除
delete from student;
truncate table studnet;
区别:
delete : DML:是逻辑删除,逐行进行删除,速度慢;
truncate: DDL操作 对与表段中的数据也进行清空,速度快;
伪删除: 用update 来替换delete,最终保证业务中查不到(select)即可
1、添加状态列并约定一个状态值;
2、需要进行delete操作时只需要修改状态列中的值即可
update
3、业务根据状态值进行查询
7、DQL 应用select
7.1 单独使用查看参数
select @@port;
select now();
select database();
select user()
select concat("helloworld");
select concat(user,"@",host) from mysql.user;
select group_concat(user,"@",host) from mysql.user;
7.2 单表查询
select * from table where k1= and k2 = group by k2 having k1= ;
等值查询
模糊查询(> ,< ,>=,<=,<>)
范围
and or between and
group by
max()
min()
count()
avg()
group_concat()
concat()
sum()
去重复:distinct()
联合查询 union all
select × from city
select * from city where countrycode IN ('CHN','USA');
select * from city where countrycode='CHN';
union all
select * from city where countrycode='USA';
说明: 一般情况下,我们会将IN或者or 语句改写成union all ,来提高性能
union: 去重复
union all: 不去重复
7.9 join 多表连接查询
按需求创建一下表结构:
use school
student :学生表
sno: 学号
sname:学生姓名
sage: 学生年龄
ssex: 学生性别
teacher :教师表
tno: 教师编号
tname:教师名字
course :课程表
cno: 课程编号
cname:课程名字
tno: 教师编号
score :成绩表
sno: 学号
cno: 课程编号
score:成绩
-- 项目构建
drop database school;
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=INNODB CHARSET utf8;
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;
image
查询张三的家庭住址
SELECT A.name,B.address FROM
A JOIN B
ON A.id=B.id
WHERE A.name='zhangsan'
SELECT b.name ,a.name ,a.population
FROM city AS a
JOIN country AS b
ON b.code=a.countrycode
WHERE a.Population<100
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';
列别名,表别名
SELECT
a.Name AS an ,
b.name AS bn ,
b.SurfaceArea AS bs,
a.Population AS bp
FROM city AS a JOIN country AS b
ON a.CountryCode=b.Code
WHERE a.name ='shenyang';
SELECT st.sname , COUNT(sc.cno)
FROM student AS st
JOIN
sc
ON st.sno=sc.sno
WHERE st.sname='zhang3'
SELECT st.sname , GROUP_CONCAT(co.cname)
FROM student AS st
JOIN sc
ON st.sno=sc.sno
JOIN course AS co
ON sc.cno=co.cno
WHERE st.sname='zhang3'
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';
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 ;
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.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 sc.score<60;
1. 查询平均成绩大于60分的同学的学号和平均成绩;
2. 查询所有同学的学号、姓名、选课数、总成绩;
3. 查询各科成绩最高和最低的分:以如下形式显示:课程ID,最高分,最低分
4. 统计各位老师,所教课程的及格率
5. 查询每门课程被选修的学生数
6. 查询出只选修了一门课程的全部学生的学号和姓名
7. 查询选修课程门数超过1门的学生信息
8. 统计每门课程:优秀(85分以上),良好(70-85),一般(60-70),不及格(小于60)的学生列表
9. 查询平均成绩大于85的所有学生的学号、姓名和平均成绩
DESC information_schema.TABLES
TABLE_SCHEMA ---->库名
TABLE_NAME ---->表名
ENGINE ---->引擎
TABLE_ROWS ---->表的行数
AVG_ROW_LENGTH ---->表中行的平均行(字节)
INDEX_LENGTH ---->索引的占用空间大小(字节)
SELECT table_schema,GROUP_CONCAT(table_name)
FROM information_schema.tables
GROUP BY table_schema;
SELECT table_schema,COUNT(table_name)
FROM information_schema.TABLES
GROUP BY table_schema
SELECT table_schema,table_name,ENGINE FROM information_schema.`TABLES`
WHERE ENGINE='innodb';
SELECT table_name,CONCAT((TABLE_ROWS*AVG_ROW_LENGTH+INDEX_LENGTH)/1024," KB") AS size_KB
FROM information_schema.tables WHERE TABLE_SCHEMA='world';
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;
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;"
模板语句:
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" )
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';
show 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 #查看从库状态
SHOW RELAYLOG EVENTS #查看从库relaylog事件信息
desc (show colums from city) #查看表的列定义信息
http://dev.mysql.com/doc/refman/5.7/en/show.html
小礼物走一走
作者:wwwoldguocom
链接:https://www.jianshu.com/p/08c4b78402ff
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
create table student (
id int not null default 0 auto_increment
);