MySQL基础操作

创建数据库

create schema 数据库名;

创建表

非空约束:not null
唯一约束:unique
主键约束:primary key(auto_increment,自增)
默认约束:default
外键约束:foreign key

//基本语法,中括号内是可以不写的
create table 表名(
	字段1 字段类型 [约束] [comment 字段1注释],
	......
) [comment 表注释];

//例如
create table tb_user(
    id int primary key auto_increment comment 'ID,唯一标识',
    username varchar(20) not null unique comment '用户名',
    name varchar(10) not null comment '姓名',
    age int comment '年龄',
    gender char(1) default '男' comment '性别'
) comment '用户表';

数据类型

数值类型

tinyint, 1, (-128, 127)
smallint, 2, (-32768, 32767)
mediumint, 3, (-8388608, 8388607)
int, 4, (-2147483648, 2147483647)
bigint, 8
float, 4, float(5, 2)表示2个小数位
double, 8
decimal, 精度更高,计算金额

字符串类型

char, (0 ~ 255), 定长字符串,性能高,浪费空间
varchar, (0 ~ 65535), 变长字符串,性能低,节省空间

日期类型

date, 3, YYYY-MM-DD, 日期值
datetime, 8, YYYY-MM-DD HH:MM:SS, 混合日期和时间值

查询、修改、删除字段和表

-- 查看当前数据库下的表
show tables;

-- 查看指定表结构
desc tb_emp;

-- 查看数据库建表语句或者直接ctrl+B
show create table tb_emp;

-- 添加字段 qq varchar(11)
alter table tb_emp add qq varchar(11) comment 'QQ';

-- 修改字段类型,把 qq 字段类型改成 varchar(13)
alter table tb_emp modify qq varchar(13) comment 'QQ';

-- 修改字段,把 qq 改成 qq_num varchar(13)
alter table tb_emp change qq qq_num varchar(13) comment 'QQ';

-- 删除字段,删除 qq_num 字段
alter table tb_emp drop column qq_num;

-- 修改表名,把 tb_emp 改成 emp
rename table tb_emp to emp;

-- 删除表
drop table if exists tb_emp;

添加、修改、删除数据

-- 为 emp 表的 username, name, gender 字段插入值
insert into emp(username, name, gender, create_time, update_time) values ('xqn', '小青年', 1, now(), now());

-- 为 emp 表的所有字段插入值
insert into emp(id, username, password, name, gender, image, job, entrydate, create_time, update_time)
            values (2, 'ruozhi', '123456', '弱智', 1, '666.jpg', 1, '2024-1-24', now(), now());

insert into emp values (3, 'ruozhi2', '123456', '弱智', 1, '666.jpg', 1, '2024-1-24', now(), now());

-- 批量为 emp 表的 username, name, gender 字段插入数据
insert into emp(username, name, gender, create_time, update_time) values
            ('lubenwei', '卢本伟', 1, now(), now()), ('mafeifei', '马飞飞', 1, now(), now());

-- 将 emp 表id为1的员工姓名name字段更新为 '张三'
update emp set name = '张三', update_time = now() where id = 1;

-- 将 emp 表所有员工的入职日期更新为 '2011-1-1'
update emp set entrydate = '2011-1-1', update_time = now();

-- 删除 emp 表中 id 为8的员工
delete from emp where id = 8;

-- 删除 emp 表中所有员工
delete from emp;

查询数据(最重要)

基本查询

-- 查询指定字段 name, entrydate
select name, entrydate from tb_emp;

-- 查询所有字段
select * from tb_emp;

-- 个查询 name, entrydate,并起别名,可以不用 as
select name as '姓 名', entrydate as 入职日期 from tb_emp;

-- 查询已有的员工关联了哪几种职位(去重)
select distinct job from tb_emp;

条件查询

比较运算符:>、>=、<、<=、=、!=、between…and…、in(…)、like、is null
逻辑运算符:and(&&)、or(||)、not(!)

-- 查询 姓名 为 杨逍 的员工信息
select * from tb_emp where name = '杨逍';

-- 查询 id 小于等于5的 员工信息
select * from tb_emp where id <= 5;

-- 查询没有分配 职位 的员工信息
select * from tb_emp where job is null;

-- 查询有 职位 的员工信息
select * from tb_emp where job is not null;

-- 查询 密码 不等于‘123456’的员工信息
select * from tb_emp where password != '123456';

-- 查询 入职日期 在'2001-01-01'到'2010-01-01'的员工信息
select * from tb_emp where entrydate between '2001-01-01' and '2010-01-01';

-- 查询 入职日期 在'2001-01-01'到'2010-01-01'且 性别 为女的员工信息
select * from tb_emp where entrydate between '2001-01-01' and '2010-01-01' && gender = 2;

-- 查询 职位 是2、3、4的员工信息
select * from tb_emp where job in(2, 3, 4);

-- 查询 姓名 为两个字的员工信息
select * from tb_emp where name like '__';

-- 查询 姓张 的员工信息
select * from tb_emp where name like '张%';

分组查询

聚合函数:count、max、min、avg、sum,不对null值进行运算
执行顺序:where > 聚合函数 > having

-- 统计该企业员工的数量
select count(id) from tb_emp;
select count(1) from tb_emp; -- 常量
select count(*) from tb_emp;

-- 统计该企业最早入职的员工
select min(entrydate) from tb_emp;

-- 统计该企业最迟入职的员工
select max(entrydate) from tb_emp;

-- 统计该企业员工id的平均值
select avg(id) from tb_emp;

-- 统计该企业员工id之和
select sum(id) from tb_emp;

-- 根据性别分组,统计男性和女性员工的数量
select gender, count(*) from tb_emp group by gender;

-- 先查询入职时间在'2015-01-01'之前的员工,并结果根据职位分组,获取员工数量大于等于2大职位
select job, count(*) from tb_emp where entrydate <= '2015-01-01' group by job having count(*) >= 2; -- having后面条件是分组之后

排序查询

升序:ASC(默认)
降序:DESC

-- 根据入职时间,对员工进行升序排序
select * from tb_emp order by entrydate asc;

-- 根据入职时间,对员工进行降序排序
select * from tb_emp order by entrydate desc;

-- 根据入职时间,对员工进行升序排序,入职时间相同,根据更新时间降序排序
select * from tb_emp order by entrydate asc, update_time desc;

分页查询

起始索引 = (页码 - 1)* 每页显示数

-- 从起始索引0开始,每页展示5条数据
select * from tb_emp limit 0, 5;

-- 查询第1页的员工数据,每页展示5条
select * from tb_emp limit 0, 5;

-- 查询第2页的员工数据,每页展示5条
select * from tb_emp limit 5, 5;

-- 查询第3页的员工数据,每页展示5条
select * from tb_emp limit 10, 5;

综合案例

格式化快捷键:ctrl + alt + l
if、case流程控制函数

-- 姓名:张 性别:男 入职时间:2000-01-01 ~ 2015-12-31 查询第一页数据,每页展示10条 根据修改时间进行降序排序
select *
from tb_emp
where name like '%张%' && gender = 1 && entrydate between '2000-01-01' and '2015-12-31'
order by update_time desc
limit 0, 10;

-- 统计员工性别信息
-- if(条件表达式, true, false)
select if(gender = 1, '男性员工', '女性员工') as 性别, count(*) from tb_emp group by gender;

-- 统计员工职位
-- case 表达式 when 值1 then 结果1 when 值2 then 结果2...else...end
select (case job when 1 then '班主任' when 2 then '讲师' when 3 then '学工主管' when 4 then '教研主管' else '未工作' end) as 职位,
count(*)
from tb_emp group by job;

多表设计

物理外键约束:外键名称 foreign key 外键字段 references 主表(很多缺点)
逻辑外键:推荐使用
一对多,在多的一方添加外键,关联另一方主键
一对一:在任意一方加入外键,关联另一方主键,并设置外键为唯一的
多对多:建立第三张中间表,中间表包含两个外键,分别关联两方主键
ctrl选中三个表,然后右键diagrams,就可以看到可视化界面

-- 案例
-- 1. 分类表category

-- 2. 菜品表 dish

-- 3. 套餐表 setmeal

-- 4. 套餐菜品关系表 setmeal_dish

-- 分类表
create table category(
     id int unsigned primary key auto_increment comment '主键ID',
     name varchar(20) not null unique comment '分类名称',
     type tinyint unsigned not null comment '类型 1 菜品分类 2 套餐分类',
     sort tinyint unsigned not null comment '顺序',
     status tinyint unsigned not null default 0 comment '状态 0 禁用,1 启用',
     create_time datetime not null comment '创建时间',
     update_time datetime not null comment '更新时间'
) comment '分类表' ;

-- 菜品表
create table dish(
     id int unsigned primary key auto_increment comment '主键ID',
     name varchar(20) not null unique comment '菜品名称',
     category_id int unsigned not null comment '菜品分类ID',
     price decimal(8, 2) not null comment '菜品价格',
     image varchar(300) not null comment '菜品图片',
     description varchar(200) comment '描述信息',
     status tinyint unsigned not null default 0 comment '状态, 0 停售 1 起售',
     create_time datetime not null comment '创建时间',
     update_time datetime not null comment '更新时间'
) comment '菜品表';
 

-- 套餐表
create table setmeal(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(20) not null unique comment '套餐名称',
    category_id int unsigned not null comment '分类id',
    price decimal(8, 2) not null comment '套餐价格',
    image varchar(300) not null comment '图片',
    description varchar(200) comment '描述信息',
    status tinyint unsigned not null default 0 comment '状态 0 停售 1 起售',
    create_time datetime not null comment '创建时间',
    update_time datetime not null comment '更新时间'
)comment '套餐' ;


-- 套餐菜品关联表
create table setmeal_dish(
     id int unsigned primary key auto_increment comment '主键ID',
     setmeal_id int unsigned not null comment '套餐id ',
     dish_id int unsigned not null comment '菜品id',
     copies tinyint unsigned not null comment '份数'
)comment '套餐菜品关系';

多表查询

笛卡尔积:所有的组合情况
连接查询:内连接:查询交集部分,外连接:左外连接:查询左表所有数据,右外连接:查询右表所有数据
子查询:查询嵌套查询
标量子查询:返回结果单个值
列子查询:返回结果一列
行子查询:返回结果一行
表子查询:返回结果多行多列

-- 部门管理
create table tb_dept
(
    id          int unsigned primary key auto_increment comment '主键ID',
    name        varchar(10) not null unique comment '部门名称',
    create_time datetime    not null comment '创建时间',
    update_time datetime    not null comment '修改时间'
) comment '部门表';

insert into tb_dept (id, name, create_time, update_time)
values (1, '学工部', now(), now()),
       (2, '教研部', now(), now()),
       (3, '咨询部', now(), now()),
       (4, '就业部', now(), now()),
       (5, '人事部', now(), now());


-- 员工管理
create table tb_emp
(
    id          int unsigned primary key auto_increment comment 'ID',
    username    varchar(20)      not null unique comment '用户名',
    password    varchar(32) default '123456' comment '密码',
    name        varchar(10)      not null comment '姓名',
    gender      tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
    image       varchar(300) comment '图像',
    job         tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
    entrydate   date comment '入职时间',
    dept_id     int unsigned comment '部门ID',
    create_time datetime         not null comment '创建时间',
    update_time datetime         not null comment '修改时间'
) comment '员工表';

INSERT INTO tb_emp
(id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time)
VALUES (1, 'jinyong', '123456', '金庸', 1, '1.jpg', 4, '2000-01-01', 2, now(), now()),
       (2, 'zhangwuji', '123456', '张无忌', 1, '2.jpg', 2, '2015-01-01', 2, now(), now()),
       (3, 'yangxiao', '123456', '杨逍', 1, '3.jpg', 2, '2008-05-01', 2, now(), now()),
       (4, 'weiyixiao', '123456', '韦一笑', 1, '4.jpg', 2, '2007-01-01', 2, now(), now()),
       (5, 'changyuchun', '123456', '常遇春', 1, '5.jpg', 2, '2012-12-05', 2, now(), now()),
       (6, 'xiaozhao', '123456', '小昭', 2, '6.jpg', 3, '2013-09-05', 1, now(), now()),
       (7, 'jixiaofu', '123456', '纪晓芙', 2, '7.jpg', 1, '2005-08-01', 1, now(), now()),
       (8, 'zhouzhiruo', '123456', '周芷若', 2, '8.jpg', 1, '2014-11-09', 1, now(), now()),
       (9, 'dingminjun', '123456', '丁敏君', 2, '9.jpg', 1, '2011-03-11', 1, now(), now()),
       (10, 'zhaomin', '123456', '赵敏', 2, '10.jpg', 1, '2013-09-05', 1, now(), now()),
       (11, 'luzhangke', '123456', '鹿杖客', 1, '11.jpg', 5, '2007-02-01', 3, now(), now()),
       (12, 'hebiweng', '123456', '鹤笔翁', 1, '12.jpg', 5, '2008-08-18', 3, now(), now()),
       (13, 'fangdongbai', '123456', '方东白', 1, '13.jpg', 5, '2012-11-01', 3, now(), now()),
       (14, 'zhangsanfeng', '123456', '张三丰', 1, '14.jpg', 2, '2002-08-01', 2, now(), now()),
       (15, 'yulianzhou', '123456', '俞莲舟', 1, '15.jpg', 2, '2011-05-01', 2, now(), now()),
       (16, 'songyuanqiao', '123456', '宋远桥', 1, '16.jpg', 2, '2007-01-01', 2, now(), now()),
       (17, 'chenyouliang', '123456', '陈友谅', 1, '17.jpg', NULL, '2015-03-21', NULL, now(), now());

-- 单表查询
select * from tb_dept;
select * from tb_emp;

-- 多表查询,笛卡尔积:所有的组合情况
select * from tb_dept, tb_emp;

-- 消除无效的笛卡尔积
select * from tb_emp, tb_dept where tb_emp.dept_id = tb_dept.id;

-- 查询员工姓名,和所属部门名称(隐式内连接)
select tb_emp.name, tb_dept.name tb1 from tb_emp, tb_dept where tb_emp.dept_id = tb_dept.id;

-- 查询员工姓名,和所属部门名称(显式内连接)
select tb_emp.name, tb_dept.name tb1 from tb_emp inner join tb_dept on tb_emp.dept_id = tb_dept.id;

-- 查询所有员工姓名,和所属部门名称(左外连接)起别名
select e.name, d.name from tb_emp e left join tb_dept d on e.dept_id = d.id;

-- 查询员工姓名,和所有部门名称(右外连接)
select e.name, d.name from tb_emp e right join tb_dept d on e.dept_id = d.id;

-- 查询教育部的部门id
select id from tb_dept where name = '教研部';

-- 查询该部门下的员工信息
select * from tb_emp where dept_id = 2;

-- 合并成一条,标量子查询
select * from tb_emp where dept_id = (select id from tb_dept where name = '教研部');

-- 查询方东白入职之后的员工信息
select * from tb_emp where entrydate > (select entrydate from tb_emp where name = '方东白');

select id from tb_dept where name in ('教研部', '咨询部');

-- 列子查询
select * from tb_emp where dept_id in (select id from tb_dept where name in ('教研部', '咨询部'));

-- 行子查询
select * from tb_emp where (entrydate, job) = (select entrydate, job from tb_emp where name = '韦一笑');

-- 表子查询
select e.*, d.name from (select * from tb_emp where entrydate > '2006-01-01') e, tb_dept d where e.dept_id = d.id;

事务

一组操作的集合,要么同时成功,要么同时失败
MySQL事务自动提交,一句话一个事务,或者使用
start transaction / begin:开启事务
commit:提交事务,全部成功了才能提交,提交了才真正执行
rollback:回滚事务,出错了,就可以恢复删除的数据

四大特性

原子性:事务是不可分割的最小单元,要么全部成功,要么全部失败
一致性:事务完成时,必须使所有数据都保存一致状态
隔离性:数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行
持久性:事务一旦提交或回滚,他对数据库中数据的改变就是永久的

索引

帮助数据库高效获取数据的数据结构,B+树(多路平衡搜索树),每个节点可以存储多个值
数据多的时候查询很慢,通过索引加快速度,空间换时间
优点:提高查询、排序的效率
缺点:占用空间大,降低增删改的效率

-- 一次性创建好索引
create index 索引名 on 表名(字段名...);

-- 查看索引
show index from 表名;

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

你可能感兴趣的:(JAVASE,mysql,数据库,java)