目录
一、简介
简介:MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。
二、分类
1、关系型数据库
数据库 有表,行,字段,约束 表与表之间存在关系
企业级数据库SqlServer MySQL POSTSql
超大型数据库 Oracal
轻量级文件数据库 Sqlite Python3内置了Sqlite
2、非关系型数据库(更加符合大数据时代需求)
文档数据库 MongoDB 数据库,集合,文档
内存数据库 Redis 数据库,键值对 结构更加宽泛
3、安装与其他
版本
企业版(收费版) 稳定 只包含最稳定的功能
社区版(免费) 免费 包含新功能 有可能不稳定
安装方式
windows安装包msi,直接根据安装向导下一步即可
windows压缩包zip,需要解压,自己配置安装
linux 在线安装sudo apt install mysql-server
mysql8 版本不在提供安装向导
默认可以使用root用户直接进入
linux targ.gz安装
官方网站 : https://www.mysql.com/
服务
sudo service mysql
Start 运行
Restart 重启
Stop 停止
ps -ef | grep mysql
数据库
结构化查询语句
DDL
数据定义语言
操作数据建库与表
DML
数据操作语言
插入、删除、修改
DQL
数据查询语言
查询
DCL
数据控制语言
用户权限控制
database
系统默认的数据库不要修改(新手期)
存储数据的仓库
用于管理表
三、sql语句
1、数据库的操作
show databases
展示所有数据库
select database()
显示当前使用的数据库 NULL表示当前没有使用数据库 ;不要忘
系统自带数据库小白最好先不要使用 创建一个自己的数据库
create database 数据库名 charset=utf8 或者 create database if not exists数据库名 charset=utf8
删除数据库
选择数据库 use 数据库名
2、数据库表的操作
查看当前数据库的所有表 (Empty还没有表)
show tables;
创建一个数据库表
create table 表名(列名 类型 约束)
查看表的详细信息
删除表
drop table 表名
修改表的名字
alter table 表名 rename 新表名
向表中添加列
alter table 表名 add 列名 类型 约束
删除表中的列
alter table 表名 drop 列名
修改列
alter table 表名 change 表名 类型 约束
3、CURD增删查改
向表中插入数据(全列插入)
insert into 表名 values(id,name,age)即使有默认值也要重新写
向表中插入数据(省略插入)
insert into 表名(属性名) values(对应属性值) 有默认值可以不用重写
查询表中的所有详细信息值
select * from 表名
通过as给与别名select 列名 as 别名 from 表名
通过条件语句查询部分行 select * from 表名 where 条件
调用函数
普通函数:
select database() 当前使用的数据库
select user() 当前连接使用者
select version()当前数据库版本信息
select current_date() 获取当前日期
select current_time() 获取当前时间戳
select utc_time() 获取当前美国时间戳
select current_timestamp() 获取当前时间日期
聚合统计函数:
select count(id) from tb 统计行数或者*(所有)
select max(id) from tb 获取最大id
select min(id) from tb 获取最小id
select sum(id) from tb 获取id总和
select avg(id) from tb 获取id 平均数
去重select distinct (去重的列)from 表名 去重重复列
排序
升序asc
降序desc
select*from 表名order by age,id desc
分组
select age,count(*) from tb group by age; 根据年龄分组
select age,count(*) from tb group by age having age > 20 根据年龄大于20分组
分页
limit count只显示前count的个数select * from tb limit 0,2从start开始数count个
修改update 表名 set 列=值,...
删除delete from 表名 清除表中值
1where 哪里where id = 1 where id > 10
and 并且or或者
between a and b范围 慎用,效率低
in 与 not in 在多个选项中就符合
null is null 为空
select * from tb where num is null
is not null非空
like % 匹配多个
_匹配一个
约束 主键约束每个表中必须有主键 主键必须唯一,能够确定唯一一行
primary key(列名)非空约束not null自增长auto_increment唯一约束不能重复unique
默认值default外键是另一个表的主键foreign key(列名) references 表名(主键名)
权限on update restrict拒绝更新
cascade级联,同步更新on delete restrict拒绝删除cascade级联,同步删除
例子
create table orders(id int not null auto_increment, uid int not null, gid int not null , num int not null, primary key(id), foreign key(uid) references user(id) on delete cascade on update cascade, foreign key (gid) references goods(id) on delete cascade on update cascade)