Mysql数据库学习及总结

前言

   本人是一名测试工程师,不管是对于数据分析师、开发工程师、测试工程师,数据库操作都是最基础也是最重要的一门技术,这篇文章就是本人在学习及工作过程对Mysql数据库的总结。


一、基础概念

1、数据库:是存储在计算机内的、有组织的、可共享的统一管理相关数据的集合,由表、关系、操作对象组成。
2、事务的特征:原子性,一致性,隔离性,持久性。
3、数据库管理系统:是一种操纵和管理数据库的大型软件,用来创建、使用、维护数据库。DDL:数据定义语言,DML:数据操纵语言,DCL:数据控制语言。
4、Mysql数据库特点:性能高效、跨平台、支持多用户、免费开源、使用简单。
5、主键:是唯一能标识某个表的记录的无具体业务含义的字段,像身份照、卡号、手机号、邮箱等都可以作为主键使用。特点:a.主键的字段具备唯一性;b.主键的字段不能为空;c.主键自带索引;d.可以多个字段组成主键;e.一个表仅一个主键。
6、外键:用于在两个表之间建立关系,需要指定引用主表的哪一列。如果表A的主键是表B中的字段,则该字段称为表B的外键,表A(主表),表B(从表)。外键是用来实现参照完整性的,主表更新时从表也更新,主表删除时如果从表有匹配的项,删除失败。
7、索引:是一种单独的、物理的对数据库表中一列或多列的值进行排序的一种存储结构。优点:使用索引能加快数据的查询速度,缺点:索引会占用内存、磁盘空间,会增加数据库管理系统的维护成本。
8、视图:一个虚表,里面不保存任何数据,视图的数据来源于创建视图时的基表。作用:简化操作、能把复杂的sql简化,B.避免数据冗余,C.提高数据安全性,D.提高数据逻辑独立性。


二、Mysql数据类型

Mysql数据类型:日期类型:date /time /datetime/timestamp,字符串类型:char/varchar/text,浮点型:decimal/float/double,整型:tinyint/smallint/mediumint/int/bigint。

Mysql中除了字符串类型需要设置长度,其他类型都有默认长度。


三、数据控制语言DCL

1、系统操作

根据进程名查端口:1.tasklist|findstr mysql  2.netstat -ano|findstr pid
根据端口查进程:1.netstat -ano|findstr port 2.tasklist |findstr pid
启动mysql服务:net start mysql
停止mysql服务:net stop mysql
访问mysql:mysql -h localhost -P 3306 -u root -p 密码
查参数:show variables;
设置参数:set 参数名称=’值’;
查当前存储引擎:show engines ;
修改当前存储引擎:set default_storage_engine=innodb;
查状态:SHOW STATUS;
查询版本:SELECT VERSION();

2、用户权限

创建用户:create user `test`@`localhost` identified by ‘123456’;
修改密码:alter user `test`@`localhost` identified by ‘123456’; 
删除用户:drop user `test`@`localhost` ;
刷新用户:flush privileges;
授予权限:grant all on *.* to `test`@`localhost` ;
撤销权限:revoke all on *.* from `test`@`localhost` ;
查询当前用户:select USER();
查看用户的权限:show grants for Fox@localhost;
查询数据库所有的用户:SELECT * FROM mysql.user;


四、数据定义语言DDL

1、建库

查所有的库:show databases;
查当前库:select database();
修改数据库:ALTER DATABASE mybase CHARACTER SET UTF8;
创建数据库:create database 数据库名 character set utf8;
查建库语句:show create database 数据库名;
删库:drop database 数据库名;
切换数据库:USE mybase;

2、建表

查所有的表:show tables;
创建表:create table exam(
    id INT(11) PRIMARY KEY AUTO_INCREMENT, -- 主键自动递增
    name VARCHAR(20) DEFAULT NULL, -- 默认为空
    English INT,
    sal DOUBLE(7,2),   --整数位7,小数位2
    Math int NOT NULL    --非空
);
添加主键:alter table stu2 add PRIMARY key (id,`name`); --指定id name一起作为主键
添加默认值:alter table stu2 alter COLUMN `gender` set DEFAULT 'm';
添加唯一约束和非空约束:ALTER TABLE exam MODIFY NAME VARCHAR(21) UNIQUE NOT NULL;
查表结构:desc 表名
查建表语句:show create table 表名;
删表:drop table 表名;
修改表名称:RENAME TABLE exam TO score;
修改表的字符集:ALTER TABLE score CHARACTER SET GBK;
create table stu4 like stu3; -- 完全复制表结构,除了数据
SHOW GLOBAL VARIABLES LIKE 'innodb_force_primary_key'; -- 查看是否开启强制主键
SET GLOBAL  innodb_force_primary_key=off; -- 关闭强制主键
mysql8以后默认开启强制主键约束,得关闭强制主键才能使用下列语句。ps:一般公司都不允许关闭强制主键。
create table stu5 as select * from stu3;-- 复制表中所有数据到新表,除了主键无法复制
create table stu6 as select id,name from stu3;--复制原表部分字段到新表,除了主键
create table stu7 as select * from stu3 where 1=0;--复制原表的表结构到新表,除了主键

3、建索引

建表时创建:
create table book(
isbn varchar(50) not null,
bookname varchar(100) not null, 
price decimal(8,2),
author varchar(50),
publishhouse varchar(50),
summary text,
PRIMARY key `pk_isbn`(`isbn`),  -- 主键索引
UNIQUE index `idx_bookname`(`bookname`), -- 唯一索引
index `idx_author`(`author`), -- 普通索引
FULLTEXT index `ft_summary`(`summary`) -- 全文索引
);

create语句:
create index `idx_author` on `book`(`author`); -- 普通索引
create UNIQUE index `idx_bookname` on `book`(`bookname`); -- 唯一索引
create FULLTEXT index `ft_summary` on `book`(`summary`); -- 全文索引

alter table 语句:
alter table book add index `idx_author`(`author`); -- 普通索引
alter table book add UNIQUE index `idx_bookname`(`bookname`); -- 唯一索引
alter table book add FULLTEXT index `ft_summary`(`summary`); -- 全文索引

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

查看索引:
SHOW INDEX FROM 表名;

4、建视图

create view 视图名(字段列表) as select 字段列表 from ......
CREATE VIEW v_studentCourseScore (
    studentno,    NAME,    coursename,    score) AS SELECT
    a.sid,    a.`name`,    b.cname,    c.number
FROM    student a,    course b,    score c
WHERE    a.sid = c.sid AND b.cid = c.corse_id;

删除视图:
drop view 视图名;

5、修改表字段

添加字段:alter table stu2 add major VARCHAR(20);
修改数据类型:alter table stu2 MODIFY major char(20);
修改字段名称:alter table stu2 change major professional char(20);
删除字段:alter table stu2 drop professional;


五、数据操纵语言DML

1、插入数据

Insert into:直接插入数据
插入一条全部字段值:insert into stu2 values(1,'zhangsan','m',20);
插入一条部分字段值:insert into stu2(id,name) values(3,'wangwu');
一次性插入多条数据:insert into stu2(id,name) values(5,'zhao7'),(6,'zhao8'),(7,'zhao9');
查询某个表的结果插入:insert into stu3(id,name,gender,age) select id,name,gender,age from stu2;

Replace into:先检查是否存在,存在则更新,不存在则插入。
Replace into 表名(字段列表) values(值列表)
Replace into 表名(字段列表) select 字段列表 from 表 [where 约束条件]
Replace into 表名 set 字段=值,字段=值

2、更新数据

update 表名 set 字段=值,字段=值 where 约束条件; --更新符合条件的行
update 表名 set 字段=值,字段=值; --更新所有行

3、删除数据

delete from 表名 where 约束条件; --删除满足条件的记录,数据可以回滚
delete from 表名; --删除全部记录,数据可以回滚
truncate table 表名; --清空表,数据无法回滚。


六、数据查询语言DQL

1、select语法格式

select 字段列表 from 表1,表2 where 约束条件 group by 分组字段 having 第二次筛选条件 order by 排序条件 limit 数量

2、基本SQL语句

查询全部数据:select * from stu;

取别名as:select name as 姓名 from stu t; -- 查询列name并取别名为姓名,表名stu为t;

排序order by:asc(升序)/desc(降序),默认是升序。
select * from stu2 order by age desc;-- 指定降序
select * from stu2 order by age asc,weight desc;-- 多个字段排序

limit关键字:
select * from stu2 limit 2; -- 返回前2行
select * from stu2 limit 1,2; -- 返回第二条 第三条,1是索引,索引从0开始

distinct剔除重复的记录:
select DISTINCT name from stu2;  --返回名字不同的记录
select DISTINCT name,age from stu2; -- 返回名字且年龄不同的记录

where条件:

关系运算符:= >= > <= < != <> <=>
select * from stu2 where weight = null;  -- 此处无法对null值进行约束,查询不到任何结果
select * from stu2 where weight <=> null; -- 可以找出weight为空的所有记录
select * from stu2 where weight >=100;--找出体重大于等于110的学生

范围查询:between and 、not between and和 in、not in
select * from stu2 where weight BETWEEN 110 and 125; -- 适合连续值的范围查询
select * from stu2 where weight in(110,120,125); -- 适合离散值的范围查询

模糊匹配:like、 not like
select * from stu2 where name like 'zhang%'; -- 以zhang开头的所有名字
select * from stu2 where name like 'zhang_'; -- 以zhang开头的后面仅1个字符的名
select * from stu2 where name like '%zhang%';-- 包含zhang的名字
select * from stu2 where name like '_zhang_';-- 中间是zhang,前后各1个字符的名字

判断是否为空:is null、is not
select * from stu2 where weight is null; -- 为空
select * from stu2 where weight is not null; -- 不为空

多条件查询:and、or
select * from stu2 where age > '18' and sex='男'; -- 查询年龄大于18岁且性别为男的记录
select * from stu2 where age > '18' or sex='男'; -- 查询年龄大于18岁或性别为男的记录

3、常用函数

数学函数:
select abs(-1.45); -- 取绝对值,输出1.45
select FLOOR(1.5); -- 向下取整,输出1
select CEILING(1.5); -- 向上取整,输出2
select mod(2,3); -- 取模
select TRUNCATE(156.567,2); --截取到小数点2位,输出156.56
select TRUNCATE(156.567,0); --截取到整数,输出156
select TRUNCATE(156.567,-2); --截取到整数2位,输出100
select ROUND(156.567,2); --四舍五入到小数点2位,输出156.57
select ROUND(156.567,0); --四舍五入到整数,输出157
select ROUND(156.567,-2); --四舍五入到整数2位,输出200

字符串函数:
select CONCAT('i','have','a','dream'); -- 字符串连接
select CONCAT_WS(' ','I','have','a','dream'); -- 字符串连接且每个单词空格隔开
select left('湖南长沙',3); -- 取左边3个字符
select right('湖南长沙',3); -- 取右边3个字符
select length('abcdefg'); -- 显示字符串的长度
select ltrim('    湖南长沙五一广场'); -- 去掉左边空格
select rtrim('湖南长沙五一广场    '); -- 去掉右边空格
select trim('    湖南  长沙  五一  广场    '); -- 去掉前后空格
select UPPER('abcd'); -- 小写变大写
select LOWER('ABCD'); -- 大写变小写
SELECT SUBSTR('123abcdABCD湖南长沙',4,3); -- 从第4位开始,截取3位,输出abc
SELECT ename,IFNULL(COMMIT,0) FROM emp; -- 如果COMMIT有null值,则显示为0
SELECT ename,CAST(sal AS INT) FROM emp; -- 把sal字段转为int类型输出
SELECT ename,COALESCE(USER,COMMIT,0) FROM emp; -- 优先取user的值,user为null,则取commit的值,commit也为null,则输出0

时间函数:
select CURDATE(); -- 查当前日期2020-11-18
select CURDATE() +0; -- 查当前日期20201118
select CURTIME(); -- 查当前时间17:55:05
select DATE_ADD('2018-02-10 10:10:10',INTERVAL 1 day); -- 加1天
select DATE_ADD('2018-02-10 10:10:10',INTERVAL -1 MONTH); -- 减1月
select DATE_ADD('2018-02-10 10:10:10',INTERVAL -1 YEAR); -- 减1年
select DAYOFWEEK('2020-11-29 10:10:10'); -- 查询星期几,输出1,1代表星期日
select DAYNAME('2020-11-29 10:10:10');  -- 查询星期的英文名称,输出Sunday
select MONTHNAME('2020-01-29 10:10:10'); -- 查询月份的英文名称,输出January
select NOW();  -- 查询当前时间
select UNIX_TIMESTAMP(); -- 查询当前时间戳

聚合函数:
select 
max(score), -- 最大值
min(score), -- 最小值
avg(score), -- 平均值
sum(score), -- 求和
count(studentNO), -- 总次数
from score;

流程函数:
SELECT IF(500<1000, 5, 10); -- 如果500<1000条件为真输出5,否则输出10;
SELECT  (CASE
WHEN state='3' THEN '失败'
WHEN state='5' THEN '成功' 
ELSE '其他' END) '状态'
FROM cm_job; -- 如果state='3'输出失败,state='5'输出成功

分组查询:
语法:Select [分组字段列表,] 聚合统计函数(...)
From 表1,表2 where 约束条件
Group by 分组字段 having 约束
order by 排序字段 排序条件
举例:查询各课程及格人数超过3个的,课程编号、人数
select major,count(*) num  from student.student 
where score >=60 GROUP BY major having num>3;

4、连接查询

笛卡尔积
select * from student a,class b;

等值连接
select a.name,b.classname from student a,class b where a.classno=b.classno;

内连接:满足连接条件的结果集。
select a.name,b.classname from student a,class b on a.classno=b.classno;
select a.name,b.classname from student a,class b on a.classno<>b.classno;

左连接:以左表为基础,结果会显示左表所有记录和右表匹配的记录、右表不匹配的用NULL代替。
select a.classname,b.name,c.score from class a LEFT JOIN student b 
on a.classNO=b.classNO left join score c on b.studentNO=c.studentNO 
where b.gender='m';

右连接:以右表为基础,结果会显示右表所有记录和左表匹配的记录、左表不匹配的用NULL代替。
select a.`name`,b.classname
from student a right join class b on a.classNO=b.classNO;

自连接:表自己和自己进行连接
select a.empno 领导编号,a.ename 领导姓名,a.job 领导职务
,b.empno 员工编号,b.ename 员工姓名,b.job 员工职务
from emp a, emp b
where a.empno=b.mgr ;

5、子查询

标量子查询:返回结果是1列1行
--查询体重最重的学生信息
select * from stu2 where weight=
(select max(weight) from stu2);

列子查询:子查询返回单列多行结果
--找出语文分数最高的学生信息
select * from student where studentno in(
select s2.studentno
from score s2,course c2 where s2.courseno=c2.courseno and s2.score=(
select s.score
from score s,course c
where s.courseno=c.courseno and c.coursename='yuwen'
order by s.score desc limit 1) and c2.coursename='yuwen')

行子查询:返回单行多列的结果
根据学号得到性别、班级编号、名字这些,再得到学生的详细信息
select * from stu2 where (gender,class,name)=
(select gender,class,name from stu2
where id=1);

表子查询:返回多行多列的结果
找各课程中成绩相同的学生信息
select * from student where studentno in(
select s2.studentno from score s2, course c2  where s2.courseno=c2.courseno and(c2.courseno,s2.score) in(
select c.courseno,s.score from score s, course c where s.courseno=c.courseno GROUP BY c.coursename,s.score having s.score>=2));

6、Exists谓词

存在则后面的sql执行,不存在则后面的sql不执行。
假如说一个学生他的语文成绩小于40,则把成绩更新成60。
update score set score=60 where score<=40 and courseno =
(select courseno from course where coursename='yuwen');

7、派生表

把sql语句返回的结果当做表来和其他表做关联,再次进行查询,这个就是派生表。
各课程分数最高的学生信息。
select * from student where studentno in(
select a.studentno 
from score a,(select courseno,max(score) ma from score group by courseno) b
where a.courseno=b.courseno and a.score=b.ma);

8、集合运算

UNION:两个查询语句把结果并到一起,剔除重复的行
UNION ALL:两个查询语句把结果并到一起,不剔除任何行
SELECT a.deptno FROM dept a UNION SELECT deptno b FROM emp;-- 查询的列必须相同

猜你喜欢

转载自blog.csdn.net/weixin_46285621/article/details/109983185
今日推荐