MySQL


MySQL 是最流行的关系型数据库管理系统,在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System:关系数据库管理系统)应用软件之一。

官网: https://www.mysql.com/

数据库和SQL是什么关系?

结构化查询语言(Structured Query Language)简称SQL,是一种特殊目的的编程语言,是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统;同时也是数据库脚本文件的扩展名。

​数据库里面放着数据,而SQL是用来操作数据库里数据的语言(工具)。

启动服务和停止服务

  • 启动、停止服务操作

    • Win+E打开资源管理器,右击此电脑-管理,选择服务和应用程序,找到对应的服务
    • services.msc打开服务管理器,找到对应服务
    • 管理员身份运行cmd,关闭服务:net stop mysql;启动服务:net start mysql
    • 创建.bat脚本,脚本内输入关闭服务:net stop mysql;启动服务:net start mysql,以管理员身份运行

进入、退出数据库

登录

命令行方式:cmd

mysql -h localhost -P 3306 -u root -p 
或者
mysql -uroot -p123456 (root是用户,123456密码)

注意:第一个-P要大写,输入完成后回车,再输入密码即可

退出

exit、quit 或者 ctrl+c

表约束

  • primary key 主键(不允许重复,不能为空)
  • auto_increment 自增
  • not null 非空
  • unique 唯一
  • charset(character set缩写) 设置编码
  • engine 设置存储引擎

常见命令

DDL - 数据库定义语言

  1. 显示数据库
show databases;
  1. 数据库创建
create database 数据库名 charset=utf8;   
  1. 数据库切换
use 数据库;
  1. 删除数据库
drop database 库名
  1. 查看当前库的所有表
show tables;
  1. 查看其他库所以表
show tables from 库名;
  1. 创建表
create table 表名(
列名 类型,
列名 类型 
);
  1. 删除表
drop table 表名;
  1. 查看建库细节
show create database 库名;
  1. 查看建表细节
show create table 表名;
  1. 修改表结构
# 添加字段
alter table 表名 add 字段名 类型;

# 重命名
alter table 表名 rename (to) 新表名;

# 重命名字段并修改类型
alter table 表名 change 字段名 新字段名 类型及约束;

# 修改字段类型
alter table 表名 modify 字段名 类型及约束;

# 删除字段
alter table 表名 drop 字段名;

DML - 数据库操作语言

插入数据(insert)

insert into 表名 (字段) valus 值;

修改数据(update)

update 表名 set 字段名 = 值 where 条件;

删除数据(delete)

delete from 表名 where 条件;

# 删除所有数据,不删除结构,会放到日志中,事务提交后才生效
delete from 表名;

# 摧毁表,删除表中所有数据,不删除结构,立即生效
truncate from 表名;

DQL - 数据库查询语言

# 查询表内所有信息
select * from 表名;

# 条件查询
select 字段名 from 表名 where 条件;

# 模糊查询 '_':匹配单个字符; '%':匹配任意长度
select 字段名 from 表名 where 字段名 like '_值';
select 字段名 from 表名 where 字段名 like '%值';

# 排序查询  order by 字段名 asc:升序(默认为升序,可以省略); desc:降序
select 字段名 from 表名 order by 字段名 (asc)/desc;

# 分页查询 limit 起始值, 步长 (起始值从0开始)
select 字段名 from 表名 limit m,n;

# 分组查询 
select 字段名, count(*) from 表名 group by 字段名 having 条件;

# 函数
# count 统计个数
select count(*) from 表名;      # 统计表里数据个数

# sum   求和
select sum(math) from 表名;     # 查询数学总成绩

# avg   平均数
select avg(chinese) from 表名;  # 查询语文平均分
select sum(chinese)/count(*) from 表名;

# max   最大值
select max(english) from 表名;  # 查询英语最高分

# min   最小值
select min(english) from 表名;  # 查询英语最低分

多表联查

select 表名.字段名 ··· from 表1, 表2, 表3 ··· where 表1.关联字段 = 表2.关联字段 and 表2.关联字段 = 表3.关联字段 ··· and 条件;

内连接:将两张表对应的数据查询出来

select 表名.字段名 ··· from 表1 inner join 表2 on 表1.关联字段 = 表2.关联字段;

左外连接:已左表为基准

select 表名.字段名 ··· from 表1 left join 表2 on 表1.关联字段 = 表2.关联字段;

右外连接:已右表为基准,

select 表名.字段名 ··· from 表1 right join 表2 on 表1.关联字段 = 表2.关联字段;

子查询(查询嵌套)

select 字段名 from 表名 where 字段名 = (select 关联字段 from 表名 where 条件);